反射的简单应用三

import java.lang.reflect.Field;

/*
 * 需求:写一个方法,  public void setProperty
 * (Object obj, String propertyName, Object value){},    
 * 此方法可将obj对象中名为propertyName的属性的值设置为value。
 * 适用场景:可以对一个类任意类型的成员变量 设置值(包括私有)
 */
public class Tool {
    public void setProperty(Object obj, String propertyName, Object value) 
            throws Exception{
        Class c = obj.getClass();
        Field f = c.getDeclaredField(propertyName);
        //设置可访问
        f.setAccessible(true);
        f.set(obj, value);
    }
}
posted @ 2016-11-13 22:34  第五个世界  阅读(66)  评论(0)    收藏  举报