Two classes with the same name in classpath

If I have two classes with the same name, tell Matcher.java in two different jar in my class path that the JVM will select, is there anyway I can suggest the JVM to choose the specific one?

+7
source share
4 answers

Quote from Oracle :

Specification Order

The order in which you specify several entries for the path to the path: important. The Java interpreter will search for classes in directories in the order in which they appear in the class path variable. In the example above, the Java interpreter first searches for the required class in the C: \ java \ MyClasses directory. Only if he does not find a class with his own name in this directory will the interpreter in the directory C: \ java \ OtherClasses look like.

Example:

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

So yes, it will load the one that appears in the above class path.

+12
source

there is a way to indicate where the class should be selected .. you can create your own class loader that will load the classes according to your requirement.

you can use your class loaded in two ways.

  • Pass it as parameter in jvm ( java -Djava.system.class.loader =com.somepackage.YourCustomClassLoader com.somepackage.YourMainClass )
  • Programmatically use the class loader to load a specific class (see links).

here are some useful links for loading classes

+1
source

The first one found on the way to classes. those. the first jar containing your class will be used.

You cannot control it from the JVM, but you can control the class path - make sure that the one you want is listed / found first in the class path.

0
source

Use the full path to the class when using it. But if you mean that a class with the same name also has the same package - correct the class path.

0
source

All Articles