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.