本帖最后由 王红霞 于 2012-8-3 17:20 编辑
class Person{
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public class reflect {
public static void main(String[] args) throws Exception {
Constructor<;Person> cons = Person.class.getConstructor(String.class,int.class);
Person p1=(Person)cons.newInstance("lisi",13);//获取实例
System.out.println(p1.getName()+":"+p1.getAge());
//利用反射的方式调用方法获取属性值
Method methodsetName = Person.class.getMethod("setName", String.class);
methodsetName.invoke(p1, "lisi");
Field fieldAge=p1.getClass().getField("age");//提示空指针异常?如何解决
fieldAge.setInt(p1, 30);
System.out.println(p1.getName()+":"+p1.getAge());
}
}
|
|