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?
class.forName() is a method in Java that returns the class object associated with the class or interface passed as the first parameter (i.e., name). This method is declared in the following way: ClassLoaders are responsible for loading classes into the memory.
Use the Class. forName() method to load the driver. The forName() method dynamically loads a Java class at runtime. When an application calls the forName() method, the Java Virtual Machine (JVM) attempts to find the compiled form (the bytecode) that implements the requested class.
ClassNotFoundException: if the class cannot be located.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With