开发者

how to avoid "duplicate class" in Java

Suppose I have have a java project myProject and am using an external library jar (someJar.jar), which has a class com.somepackage.Class1.class.

Now I find an updated version of Class1.java which fixes a bug in the original jar.

I include the new Class1.java in my source code under package com.somepackage

When I build the project (e.g., using Netbeans), there is a dist\myProject.jar which contains the classcom.somepackage.Class1.class and a dist\lib\someJar.jar which also contains a class with the same name.

When I run the file (e.g, using java -jar dist\myProject.jar), the new version of Class1.class is used (as I want).

  1. How does Java decide which class file to run in case of such duplicates? Is there any way I can specify precedence ?

  2. Is there any 'right' way to avoid such clashes?

  3. In Proguard, when I try to compress my code, I get a duplicate class error. H开发者_开发知识库ow do I eliminate this?


  1. Java decides which one to use based on the order of the classpath. List yours first and you'll be fine.

  2. The "right" way would be to fix the orignal source, but sometimes that's not always an option.

  3. I haven't used ProGuard, but I have re-jarred libaries before that had duplicate classes. The solution in my case was to tell Ant to ignore duplicate classes. I would assume ProGuard would have that support too.


Can you not create an updated jar file which contains the bug fix? It's going to make things a lot simpler if you don't have two versions of the same fully-qualified class around.


1) Updated Jar is a better solution.

2) Use a different class name. Is there a reason, why you want to use the same class name and same packing? I don't think there is a reason.

3) create a wrapper/ proxy class, that encapsulate all the calls to the jar and you can decide to call this new class that fixes the bug ( provided it has a different name and packaging)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜