黑马程序员技术交流社区
标题:
用反射获取构造函数时,报java.lang.NoSuchMethodException!
[打印本页]
作者:
李震 李震 李震
时间:
2012-4-4 11:23
标题:
用反射获取构造函数时,报java.lang.NoSuchMethodException!
package itcast.javabean;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package itcast.javabean;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class BeanReflection {
public static void main(String[] args) throws Exception {
Constructor[] constructor=Class.forName("itcast.javabean.Person").getConstructors();
System.out.println(constructor.length);
for(Object obj:constructor){
System.out.println(obj);
}
Constructor constructor1=Class.forName("itcast.javabean.Person").getConstructor(Person.class);
System.out.println(constructor1);
}
}
我能获取到所有的构造函数,为什么我获取单个构造函数的时候就给我报java.lang.NoSuchMethodException!
_G2L}AV)H11SWQTG9Q9DQ3P.jpg
(38.85 KB, 下载次数: 82)
下载附件
2012-4-4 11:22 上传
求教啊?
作者:
foxpeter
时间:
2012-4-4 11:49
Constructor constructor1=Class.forName("itcast.javabean.Person").getConstructor(Person.class);
这里的参数传错了吧 应该传的是这个构造函数参数的类型
作者:
李敏
时间:
2012-4-4 11:50
public class BeanReflection {
public static void main(String[] args) throws Exception {
Constructor[] constructor=Class.forName("itcast.javabean.Person").getConstructors();
System.out.println(constructor.length);
for(Object obj:constructor){
System.out.println(obj);
}
Constructor constructor1=Class.forName("itcast.javabean.Person").getConstructor(Person.class);//-----------此处错误。如果你想得到两个参数的那个构造函数
//应该是getConstructor(String.class,int.class);
System.out.println(constructor1);
}
}
作者:
李震 李震 李震
时间:
2012-4-4 12:10
恩 谢谢了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2