java 类路径中具有相同名称的两个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6935705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two classes with same name in classpath
提问by java4me
If I have two classes with same name say Matcher.java in two different jar in my classpath which one will be picked up by JVM , is there anyway I can suggest JVM to pick a specific one ?
如果我有两个同名的类,在我的类路径中的两个不同的 jar 中说 Matcher.java,其中一个将由 JVM 选择,无论如何我可以建议 JVM 选择一个特定的吗?
回答by zw324
Quoting 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. In the example above, the Java interpreter will first look for a needed class in the directory 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.
规格顺序
指定多个类路径条目的顺序很重要。Java 解释器将按照它们出现在类路径变量中的顺序在目录中查找类。在上面的示例中,Java 解释器将首先在目录 C:\java\MyClasses 中查找所需的类。只有在该目录中没有找到具有正确名称的类时,解释器才会在 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.
所以是的,它会加载第一个指定的类路径中出现的那个。
回答by Bohemian
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 cancontrol the classpath - make sure the one you want is listed/found first in the classpath.
您无法从 JVM 内控制它,但您可以控制类路径 - 确保您想要的那个在类路径中首先列出/找到。
回答by Anantha Sharma
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
您可以使用两种方式加载的类
- Pass it as a parameter to jvm (
java -Djava.system.class.loader =com.somepackage.YourCustomClassLoader com.somepackage.YourMainClass
) - Use the class loader programatically to load a specific class (refer the links provided).
- 将其作为参数传递给 jvm (
java -Djava.system.class.loader =com.somepackage.YourCustomClassLoader com.somepackage.YourMainClass
) - 以编程方式使用类加载器加载特定类(请参阅提供的链接)。
here are some useful links on class loading
这里有一些关于类加载的有用链接
回答by Andrew Thompson
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.
使用时使用类的完全限定路径。但是如果你的意思是同名的类也有相同的包 - 修复类路径。