Loading two classes in different JARs

asgs picture asgs · Apr 28, 2011 · Viewed 8.7k times · Source

I got two classes with the same package in different JARs. Until the previous version, both classes were identical, so i had no issues in loading them. Now, one of them has a new method added and if I want to access it, not only should I import the class with that package, i also need to make sure the jar with the correct class comes first in the classpath.

i.e. javac -classpath "%classpath%;a.jar;b.jar" MyClasses..

where a.jar has the class with my new method.

Now, how do i ensure this when my app goes to production, where it's deployed as an EAR file, with all the libraries under WEB-INF/lib?

How do I know which jar gets the preference over the other? Is it the alphabetical order like a.jar is given the first preference over b.jar?

I've read this safe-class-imports-from-jar-files thread and got to know about writing a custom classloader, but is there a better simpler solution that? Cos I'm just going to access this method in that whole JAR in this current project and writing a classloader seems a bit overkill.

And please don't ask me "Why the hell same class with same package in different JARs?" It's absolutely out of my control and it'll take some time to get this corrected.

Environment details: IBM WAS 6.1 on their 1.5 Java.

Please ask me more questions, if I don't make much sense. Thanks in advance!

Answer

DaveH picture DaveH · Apr 28, 2011

As far as I know, the order of jars being loaded from WEB-INF/lib is arbitrary - I asked a similar question about JBOSS and got the reply ( from RedHat ) that it depends on the order that java.io.File.listFiles() returns them in ( and that is not a guaranteed order ).

A custom classloader would be an option, but have you considered repackaging the jars - removing the duplicated classes?