Import conflict - because of same package structur

2019-09-01 02:42发布

问题:

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.

回答1:

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");


回答2:

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.