I cannot seem to get Class.forName(String)
to not throw a ClassNotFoundException
. For example, this code which is a shortened copy of code directly from Sun's website throws the exception.
import java.lang.reflect.*;
class A {}
public class Test {
public static void main(String args[])
{
try {
Class cls = Class.forName("A");
}
catch (Throwable e) {
System.err.println(e);
}
}
}
Produces
java.lang.ClassNotFoundException: A
I am using Eclipse 1.3.2.20110218-0812 on Windows XP SP3. Does anyone know what I am missing?
You have to prepend the package name of the Test class to A, as an example if Test were in "test" package, you'd need following:
Class cls = Class.forName("test.A");
Your snippet works fine for me.
Here is a demo at ideone.com: http://ideone.com/IBjKl
Note that you need to provide the fully qualified name of the class for the class loader to find it. I.e., if A
is actually in some package, you need to do forName("your.package.A")
for it to work.
(Note that the import is unnecessary.)
Class.forName
function needs the fully specified class path. So even if you have imported ArrayList
from java.util
you should use:
Class myClass = Class.forName("java.util.ArrayList");
that is your problem.
For this to work, you need to have a class with name "A" in your classpath