Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of having duplicate classes in java jar?

I am building java jar file using ant. I need to include additional jars using "zipfileset src="xxx.jar" "zipfileset src="yyy.jar" and both xxx.jar and yyy.jar have the classes with the SAME fully-qualified class names. So the resulting jar file has duplicate class names. What are the possible implications of having duplicates?

Thank you.

like image 921
romeo romeo Avatar asked Jan 24 '12 21:01

romeo romeo


People also ask

What is duplicate class in Java?

The "duplicate class" error can also occur when the class is named the same with the same package naming hierarchy, even if one of the classes exists in a directory structure with directory names different than the package names. This is shown in the next screen snapshot.

What happens if we put two different versions of jar files in classpath?

There is only a conflict if both jars define the exact same fully qualified class names. The JVM will most definitely load both jars - but it will not load classes from them that are already loaded.

Does order of classpath jars matter?

It is specified by the order in which the resources (i.e. usually jar files) are specified using -classpath option. Resources 'earlier' on the classpath take precedence over resources that are specified after them.

When a referenced class can't be loaded by the JRE which exception is thrown by?

2. ClassNotFoundException. ClassNotFoundException is a checked exception which occurs when an application tries to load a class through its fully-qualified name and can not find its definition on the classpath. This occurs mainly when trying to load classes using Class.


2 Answers

If they're duplicate implementations, nothing–it wouldn't matter which is loaded.

If not, you're at the mercy of class load order, and may get a different version than you want.

It is specified that classpath entries will be searched in the order listed (as per this classpath doc). but that's only relevant if you're in complete control of classpath creation (unlike in a web app, for example).

(With the caveat that classpath wildcarding makes the order non-deterministic.)

like image 86
Dave Newton Avatar answered Sep 18 '22 13:09

Dave Newton


In general this situatioin is highly non recommended and should be avoided.

Jars in java are just containers for your class files. java uses classloaders that look at the classpath and load class files from there. so if you have 2 jars A.jar and B.jar that have the same class x.y.Foo inside, the class from the jar that comes first in the classpath will be loaded. So, if your classpath is A.jar,B.jar (in this order) the class Foo from A.jar will be used in runtime. This inconsistency can lead to very hard-to-fix bugs from my experience

like image 26
Mark Bramnik Avatar answered Sep 21 '22 13:09

Mark Bramnik