[英]How do I choose which library a class will be imported from in Java?
I have two versions of a Java library model.jar
, each with the same set of classes (but different implementations). 我有两个版本的Java库
model.jar
,每个版本都有相同的类集(但实现不同)。 I want to write a Java class that imports some classes from one version, and imports some from the other version. 我想编写一个Java类,从一个版本导入一些类,并从另一个版本导入一些类。
I know I can include both in compilation by giving them different names: 我知道我可以通过给他们不同的名字包括在编译中:
javac -cp model.jar;model2.jar MyClass.java
But any import
statement will import the corresponding class from the first .jar file I specify in the classpath. 但是任何
import
语句都会从我在类路径中指定的第一个.jar文件中导入相应的类。
Can I specify in my import
statement which library to import from, given that the library structure will be the same for both files? 我可以在我的
import
语句中指定要从哪个库导入,因为两个文件的库结构是相同的吗?
It is not possible (well actually, at least not that simply). 这是不可能的(实际上,至少不是那么简单)。
Depending on what you are trying to achieve, if you really have to use two versions of a library, you can try a module system like OSGi , Jboss-Modules , or something like that. 根据你想要实现的目标,如果你真的必须使用两个版本的库,你可以尝试像OSGi , Jboss-Modules等类似的模块系统。
If the classes have the same name (including the package) there is no chance unless you work with different class loaders. 如果类具有相同的名称(包括包),除非您使用不同的类加载器,否则没有机会。 Java will always use the first matching class it finds on the class path.
Java将始终使用它在类路径上找到的第一个匹配类。
Moreover, nasty problems may arise if you use the same library in different versions. 此外,如果您在不同版本中使用相同的库,可能会出现令人讨厌的问题。 You should really try to resolve this in another way.
你应该尝试以另一种方式解决这个问题。
You can't like this. 你不能这样。
The only thing you can do is to use a script to generate one jar from the two with the classes that you want, and put that jar in the classpath 你唯一能做的就是使用一个脚本从你想要的类中生成两个jar,然后将jar放在类路径中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.