I was trying this sample code of reflection :
import java.lang.reflect.Method;
class Test
{
public Test()
{ }
public void sayHello()
{
System.out.println("Hello");
}
}
public class Foo
{
public static void main (String[] args) throws Exception
{
Class<?> clazz = Class.forName("Test");
Method method = clazz.getMethod("sayHello");
Object instance = clazz.newInstance();
method.invoke(instance);
}
}
The following is the error that is been displayed :
run:
Exception in thread "main" java.lang.ClassNotFoundException: Test
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at foo.Foo.main(Foo.java:29)
Java Result: 1
How can, I solve the above error in the code. I also gave Foo.Test but it does not work at all.
Please help me resolve this. Thank you
From the Stack trace you've provided, it seems you have a package foo. In order for this to work try to replace your implementation with the following:
Class<?> clazz = Class.forName("foo.Test");
N.B. Always remember that for reflection to work, you will be required to provide the full class name including the package.