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

天大地大妈咪最大 提交于 2019-12-17 10:59:46

问题


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.


回答1:


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.)




回答2:


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




回答3:


whats mean duplicated? it's obvious that you can not have 2 classes with the same name in the same package (even your project will not compile), but if you mean that you have 2 classes with the same name in different packages that's "is ok".




回答4:


I agree with Dave.

Can you separate them by namespace to avoid the pitfalls he suggests?




回答5:


Another answer which I don't see discussed here is that if you plan on signing your jars, aars, apks then it signjar will complain that you have duplicate entries

jarsigner: unable to sign jar: java.util.zip.ZipException: duplicate entry: com/foo/bar/baz.java


来源:https://stackoverflow.com/questions/8994147/what-are-the-implications-of-having-duplicate-classes-in-java-jar

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