在创建使用Class.forName()的对象时,我遇到了错误。你能否确认我做错了什么。
Exception in thread "main" java.lang.ClassNotFoundException: ABC
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at RandomPrograms.ClassObjectFromString.main(ClassObjectFromString.java:32)
ClassObjectFromString.java
import java.lang.reflect.Constructor;
class ABC {
ABC() {
System.out.println("ABC called!!! ");
}
ABC(String a) {
System.out.println("ABC called : " + a);
}
}
class ClassObjectFromString {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("ABC");
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { "Message" });
}
}
答案 0 :(得分:3)
public static Class<?> forName(String className)
提供包含您的包名称的所需类的完全限定名称。我们会RandomPrograms.ABC
答案 1 :(得分:0)
这里有一些问题:
所以你的代码应该是这样的(假设包名是RandomPrograms,根据需要替换你的代码):
public class ClassObjectFromString {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("RandomPrograms.ABC");
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { "Message" });
}
}
class ABC {
public ABC() {
System.out.println("ABC called!!! ");
}
public ABC(String a) {
System.out.println("ABC called : " + a);
}
}