Where does Class.forName(String className) look for the class name?

class, instance, java, package, project

Solution

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.

Problem

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

Original source

Related problems