Reputation: 133
When I user java reflection to create object,It will throw an "java.lang.ClassNotFoundException",this is my code:
public class Demo {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("Demo");
Demo d = (Demo) clazz.newInstance();
}
}
where I was wrong.
Upvotes: 0
Views: 349
Reputation: 6723
Or, bonus points for a java.lang.invoke
based solution :)
MethodType mt; MethodHandle mh;
MethodHandles.Lookup lookup = MethodHandles.lookup();
mt = MethodType.methodType(void.class);
try {
Class klass = Class.forName("com.mycompany.mypackage.Demo");
mh = lookup.findConstructor(klass, mt);
Object obj = (Object)mh.invoke();
} catch (Throwable ex) {
// ERR
System.out.println(ex);
}
Upvotes: 0
Reputation: 424983
You must use the fully qualified name of the class, ie including the package, eg:
public class Demo {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.mycompany.mypackage.Demo");
Demo d = (Demo) clazz.newInstance();
}
}
Upvotes: 10