I looked on http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html and saw that class.forname(String className)and "Returns the Class object associated with the class" Where does this method look for the class? Is it in the package of java project of the class in which the method was called? What if there are multiple classes with the same name? The Api doesnt discuss these situations
-
The default place to look is in the folder that you run the program from. If you are in bin and are loading `/some/package/Myclass`, it will search for `bin/some/package/Myclass.class`. However, I am not sure what happens if you have multiple folders in your path and multiple files exist (though I assume this would give you an exception of some kind). – Pphoenix Jul 09 '14 at 08:43
3 Answers
If you carefully read the JavaDoc you'll see the following:
Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to:
Class.forName(className, true, currentLoader)
where currentLoader denotes the defining class loader of the current class.
This means that the class will be loaded from the current classloader and if there is no such class, the classloader will most probably delegate to its parent (the exact behavior depends on what classloader it is).
What if there are multiple classes with the same name?
As said above, the classloader hierarchy will try to load the most specific class, i.e. from the most specific classloader that knows a class of that name.
Since the classname has to be the fully qualified classname, i.e. "java.lang.String"
instead of only "String"
this would be unique per classloader.
If you have multiple libraries containing the same classes on your classpath it depends on the classloader and the classloader hierarchy which of those classes is loaded and returned.

- 87,414
- 12
- 119
- 157
It looks for given class in the classpath. If multiple classes with the same package/name exist, first one is used.

- 1,732
- 1
- 22
- 37
-
-
http://stackoverflow.com/questions/11613988/how-to-get-classpath-from-classloader – bigGuy Jul 09 '14 at 08:58
Firstly it will look in the current project and if it found then it will stop searching..
Secondly if it doesn't find then it check in the dependent jars which are inbuilt jars of jdk.. if it still doesn't find then it look in the external jars..
in this process, if it find in between it will stop searching.. so even there are multiple classes with same name, no problem.. it takes only one..
Importantly any class is loading by JVM only once..

- 3,389
- 9
- 42
- 66
-
1`Importantly any class is loading by JVM only once..` not exactly, it would be once per classloader and you can have multiple of those. – Thomas Jul 09 '14 at 08:52
-
@Thomas Thanks for correcting me.. I even know that class loader subsystem only loads classes only once.. but while typing suddenly JVM came to mind.. :P – Mr.Chowdary Jul 09 '14 at 08:59