下面是实体类
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
private int age;
}
下面是测试类
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Constructor constructor = Person.class.getConstructor(String.class,Integer.class);
String name="刘阳";
Integer weight=new Integer(23);
Object initargs []={name,weight};
Person p =(Person)constructor.newInstance(initargs);
System.out.println("姓名:"+p.getName()+"年龄:"+p.getAge());
Person pa = new Person("liuyang",12);
Method methodSetName = Person.class.getMethod("setName", String.class);
methodSetName.invoke(pa, "刘");
System.out.println(pa.getName());
}
}
下面是报的错:
Exception in thread "main" java.lang.NoSuchMethodException: Person.<init>(java.lang.String, java.lang.Integer)
at java.lang.Class.getConstructor0(Class.java:2706)
at java.lang.Class.getConstructor(Class.java:1657)
at ReflectTest.main(ReflectTest.java:13)
|