问题描述
我的代码对abc.jar文件具有依赖性.此abc.jar文件在软件包org.apache.log4j下有一个名为logger的类,但这不是apache的记录器.
我想使用来自Apache的Logger.我在Apache的记录器中添加了Maven中的依赖性.但是问题是,当我想使用Apache的记录器时,它会自动从ABC.Jar文件拾取记录器.
推荐答案
当两个JAR都具有相同的类名称时,要从特定jar加载类.
1)您需要指定需要使用类的JAR的路径.
这样做可以使用
URL myURL = new URL("jar:file:" +OfficialApacheJarPath+"!/"); URL[] urls = new URL[]{myURL}; URLClassLoader cl = URLClassLoader.newInstance(urls); Class c = cl.loadClass("Logger");
其他推荐答案
要防止这种碰撞,您应该使用完整的合格类名称.e.g. org.apache.log4j.logger logger = new org.apache.log4j.logger();
使用完全合格的软件包名称通常被认为是糟糕的样式,除非有必要避免碰撞.
问题描述
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.
推荐答案
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");
其他推荐答案
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.