Import conflict - because of same package structure

人走茶凉 提交于 2019-12-11 18:37:40

问题


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.



来源:https://stackoverflow.com/questions/34609090/import-conflict-because-of-same-package-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!