Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two classes with same name in classpath

Tags:

java

classpath

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 ?

like image 385
java4me Avatar asked Aug 04 '11 02:08

java4me


People also ask

Can 2 class have same name?

In fact, you can't create two public classes in a single file, Only one class should be public and it should be the name of the class. If you try to create two public classes in same file the compiler generates a compile time error.

Can 2 classes have same name in Java?

For convenience, Java allows you to write more than one method in the same class definition with the same name. For example, you can have two methods in ShoppingCart class named computeCost. Having two or more methods named the same in the same class is called overloading.

Can same class be loaded twice in JVM?

Yes, you can import a class twice in Java, it doesn't create any issues but, irrespective of the number of times you import, JVM loads the class only once.

Can a package can have two or more classes with the same name within the same package?

Yes there is. You would need to implement your own Classloader and play some games to be able to access both during runtime.


2 Answers

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.

like image 187
zw324 Avatar answered Oct 13 '22 08:10

zw324


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.

like image 34
Bohemian Avatar answered Oct 13 '22 07:10

Bohemian