18.4.3访问属性值(给属性设置值)

package d18_4_2;

import java.lang.reflect.Field;

/**
 * Field
 *    getXxx(Object obj):获取obj对象的F属性值,
 *    setXxx(Object obj,Xxx val):将obj对象的该Field设置成val值
 *    注意  : Xxx对应8个基本类型,若是引用类型,则取消set/get后面的Xxx
 *
 */
public class FieldInvoke {

	public static void main(String[] args) throws Exception {
		Class c=Test2.class;
		Test2 t=(Test2)c.newInstance();
		Field f = c.getDeclaredField("uname");
		f.setAccessible(true);//设置该Field取消访问权限检查
		f.set(t,"张三");
		System.out.println(f.get(t));
		
		Field f2 = c.getDeclaredField("age");
		f2.setAccessible(true);//设置该Field取消访问权限检查
		f2.setInt(t,20);
		System.out.println(f2.getInt(t));
	}

}
class Test2{
	private String uname;
	private int age;
}

  

posted @ 2017-08-14 23:07  奋斗的少年WH  阅读(129)  评论(0编辑  收藏  举报