反射应用--修改属性值

public class test3 {
    /*
     * public void setProperity(object obj,String name, object value)
     * 此方法可将obj对象中的名为properityName的属性值 改为 value
     */
    public static void main(String[] args) throws Exception {
        Student s = new Student("张三",23);
        System.out.println(s);
        Tool t = new Tool();
        t.setProperity(s, "name", "李四");
        System.out.println(s); 
    }

}
import java.lang.reflect.Field;

public class Tool {
    public void setProperity(Object obj,String name, Object value) throws Exception{
        Class clazz = obj.getClass();
        Field f = clazz.getDeclaredField(name);
        f.setAccessible(true);        //取出权限
        f.set(obj, value);
    }
}
竹杖芒鞋轻胜马,一蓑烟雨任平生。 回首向来萧瑟处,也无风雨也无晴。
原文地址:https://www.cnblogs.com/yaobiluo/p/11359900.html