本帖最后由 杨剑 于 2013-3-15 16:02 编辑
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args) throws Exception{
Class cls2 = Person.class;
Constructor con2 = cls2.getConstructor(String.class,int.class,String.class);
Person p2 = (Person)con2.newInstance("lisi",21,"w");
Field field2 = cls2.getDeclaredField("name");
field2.set(p2, "wangwu");
String name = (String)field2.get(p2);
System.out.println(name);
}
}
class Person {
private String name;
public int age;
public String sex;
public Person(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
}
修改name属性的值,总是修改不成功,前面修改age就成功了。
|