Import conflict - because of same package structur

2019-09-01 02:23发布

My code has a dependency on abc.jar file. This abc.jar file has a class called Logger, under the package org.apache.log4j, but this is not the Logger from Apache.

I want to use Logger from Apache. I have added a dependency in maven for Apache's Logger. But the problem is that when I want to use Apache's Logger, it automatically picks up the Logger from abc.jar file.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-01 02:54

To load class from specific JAR when both JAR has same Package with same class name.

1) You need to specify the path of the JAR from which you need to use the class.

To do so you can use

URL myURL = new URL("jar:file:" +OfficialApacheJarPath+"!/");
    URL[] urls =  new URL[]{myURL};
    URLClassLoader cl = URLClassLoader.newInstance(urls);
    Class c = cl.loadClass("Logger");
查看更多
闹够了就滚
3楼-- · 2019-09-01 03:09

To prevent such collision, you should use the full qualified class name.e.g. org.apache.log4j.Logger logger = new org.apache.log4j.Logger();

Using fully qualified package names is usually considered poor style, except when it is necessary to avoid collisions.

查看更多
登录 后发表回答