开发者

Two classes with same name in classpath

开发者 https://www.devze.com 2023-03-25 08:28 出处:网络
If I have two c开发者_Python百科lasses 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 on

If I have two c开发者_Python百科lasses 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 ?


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.

The example mentioned:

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.

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.


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

  1. Pass it as a parameter to 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

  • Oracle - How to write your own class loader
  • A very nice post on writing custom class loader


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.

0

精彩评论

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

关注公众号