Say I have the following two classes:
public class MyClass {
public String getDescription() {
return "MyClass";
}
}
and
public class MyClassLoader {
public static void main (String[] argv) throws ClassNotFoundException {
Class.forName("MyClass");
System.out.println("MyClass class was successfully loaded");
}
}
If both of these classes are in the default package, it runs fine, the class loads, and the world is beautiful. (If I were to delete the class MyClass
, I would get a ClassNotFoundException
, as expected.
However, if they are both in a package (let's say it's a package in Eclipse), and have the
package myClassTestPackage;
declared in both, I get a ClassNotFoundException
when I try to run it.
What causes this issue and how can I fix it? This is the simplest way I was able to reproduce an error I am experiencing in a much larger program.
That's because the Class.forName() method takes the fully qualified class name as parameter.
Parameters:
className - the fully qualified name of the desired class.
So:
Class.forName("myClassTestPackage.MyClass");