简体   繁体   English

classpath中具有相同名称的两个类

[英]Two classes with same name in classpath

如果我有两个同名的类在我的类路径中的两个不同的jar中说Matcher.java,其中一个将由JVM拾取,那么我是否可以建议JVM选择一个特定的?

Quoting Oracle : 引用Oracle

Specification order 规格订单

The order in which you specify multiple class path entries is important. 指定多个类路径条目的顺序很重要。 The Java interpreter will look for classes in the directories in the order they appear in the class path variable. Java解释器将按照它们在类路径变量中出现的顺序查找目录中的类。 In the example above, the Java interpreter will first look for a needed class in the directory C:\\java\\MyClasses. 在上面的示例中,Java解释器将首先在目录C:\\ java \\ MyClasses中查找所需的类。 Only if it doesn't find a class with the proper name in that directory will the interpreter look in the C:\\java\\OtherClasses directory. 只有当它在该目录中找不到具有正确名称的类时,解释器才会查看C:\\ java \\ OtherClasses目录。

The example mentioned: 提到的例子:

C:> java -classpath C:\\java\\MyClasses;C:\\java\\OtherClasses ... C:> java -classpath C:\\ java \\ MyClasses; C:\\ java \\ OtherClasses ...

So yes, it will load the one appears in the classpath that specified first. 所以是的,它将加载出现在首先指定的类路径中的那个。

The first one found in the classpath. 第一个在类路径中找到。 ie, the first jar containing your class will be used. 即,将使用包含您的类的第一个jar。

You can't control it from within the JVM, but you can control the classpath - make sure the one you want is listed/found first in the classpath. 您无法从JVM中控制它,但您可以控制类路径 - 确保在类路径中首先列出/找到您想要的那个。

there is a way for you to specify where the class should be picked from.. you can create your own class loader which would load classes according to your requirement. 有一种方法可以指定应该从哪个类中选择...您可以创建自己的类加载器,它将根据您的要求加载类。

you can use your class loaded in 2 ways 你可以用2种方式加载你的类

  1. Pass it as a parameter to jvm ( java -Djava.system.class.loader =com.somepackage.YourCustomClassLoader com.somepackage.YourMainClass ) 将它作为参数传递给jvm( java -Djava.system.class.loader =com.somepackage.YourCustomClassLoader com.somepackage.YourMainClass
  2. Use the class loader programatically to load a specific class (refer the links provided). 以编程方式使用类加载器来加载特定的类(请参阅提供的链接)。

here are some useful links on class loading 这里有一些关于类加载的有用链接

Use the fully qualified path of the class when using it. 使用时使用类的完全限定路径。 But if you mean the class with the same name also has the same package - fix the class-path. 但是,如果您的意思是具有相同名称的类也具有相同的包 - 修复类路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM