如何避免“重复课程”在Java中 [英] how to avoid "duplicate class" in Java

查看:194
本文介绍了如何避免“重复课程”在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个java项目 myProject 并且正在使用外部库jar( someJar.jar ),它有一个类 com.somepackage.Class1.class



现在我找到<$ c的更新版本$ c> Class1.java 修复了原始jar中的错误。



我包含新的 Class1.java 在我的源代码包 com.somepackage



当我构建项目时(例如,使用Netbeans),有一个 dist\myProject.jar ,其中包含类 com.somepackage.Class1.class dist\lib\someJar.jar 其中还包含一个同名的类。



当我运行文件时(例如,使用 java -jar dist\myProject.jar ),新版本的 Class1.class (按照我的意愿)。


  1. 如果出现这样的重复,Java如何决定运行哪个类文件?有什么方法可以指定优先顺序吗?


  2. 有没有正确的方法来避免这种冲突?


  3. 在Proguard中,当我尝试压缩代码时,出现重复类错误。如何消除这种情况?



解决方案


  1. Java根据类路径的顺序决定使用哪一个。先列出你的,你会没事的。


  2. 正确的方式是修复原始来源,但有时这并不总是一种选择。 / p>


  3. 我没有使用过ProGuard,但是在重复上课之前我已经重新激活了库。我的解决方案是告诉Ant忽略重复的类。我认为ProGuard也会得到这种支持。



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

这篇关于如何避免“重复课程”在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆