質問

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.

他のヒント

You have to provide the fully-qualified name of the class (which includes the package and the name of the class). For example:

Class<?> clazz = Class.forName("foo.Test");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top