public static void testTT() throws Exception {
Class<?> clazz = Class.forName("reflect.Person");
// 获得构造器
Constructor<?> constructor = clazz.getDeclaredConstructor(new Class[] {});
// 根据类的默认构造器来获得一个对象
Object instance = constructor.newInstance(new Object[] {});
System.out.println(instance);
Constructor<?> constructor2 = clazz
.getDeclaredConstructor(new Class[] { Integer.class, String.class, Integer.class });
Object instance2 = constructor2.newInstance(new Object[]{1,"Tom",21});
System.out.println(instance2);
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
Exception in thread "main" java.lang.NoSuchMethodException: reflect.Person.<init>(java.lang.Integer, java.lang.String, java.lang.Integer)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
Constructor<?> constructor2 = clazz.getDeclaredConstructor(new Class[] { int.class, String.class, int.class });
你没有3个参数的构造,所以就错了,
sorry,刚没看到,你把那段代码改下:Constructor<?> constructor2 = clazz.getDeclaredConstructor(new Class[] { Integer.class, String.class, Integer.class });
改为:Constructor constructor2 = clazz.getDeclaredConstructor(new Class[] { Integer.class, String.class, Integer.class });
如此ok,注意"?"代表统配!!!何为统配?就是所有类都适用,何为所有类都适用?Object,然而Object没有有参构造,所以报上述错误,这里你最好采用自定义泛型,也就是假如你的工厂类为Factroy,定义为Factroy,然后Constructor就ok了,调用的时候需要出入泛型,传入Person.class,然而这里你没有定义泛型,所以当前代码解决方法如上述所说,Constructor如此解决,欢迎采纳!!!
Person类缺少无参构造方法,JAVA写了自己的构造方法以后,无参数的构造方法就认为不存在了,如果需要无参数的构造方法需要自己写出来。
解决方式:在你的Person类中加入无参数的构造方法
public Person() {
}