首页 > 基础教程 > 反射 > Reflection API
Java Field.set()向对象的这个Field属性设置新值value
定义
set(Object obj, Object value)
将指定对象变量上此 Field 对象表示的字段设置为指定的新值.
//根据属性名设置它的值
A a = new A();
Field field = a.getClass().getDeclaredField("x");
field.setAccessible(true);
field.set(a, 1);
例子
获取属性的属性值并修改属性值
public static void main(String[] args) throws NoSuchFieldException,
SecurityException,
IllegalArgumentException,
IllegalAccessException {
Person person = new Person();
person.setName("VipMao");
person.setAge(24);
person.setSex("男");
//通过Class.getDeclaredField(String name)获取类或接口的指定属性值。
Field f1 = person.getClass().getDeclaredField("name");
System.out.println("-----Class.getDeclaredField(String name)用法-------");
System.out.println(f1.get(person));
System.out.println("-----Class.getDeclaredFields()用法-------");
//通过Class.getDeclaredFields()获取类或接口的指定属性值。
Field[] f2 = person.getClass().getDeclaredFields();
for (Field field: f2) {
field.setAccessible(true);
System.out.println(field.get(person));
}
//修改属性值
System.out.println("----修改name属性------");
f1.set(person, "Maoge");
//修改后再遍历各属性的值
Field[] f3 = person.getClass().getDeclaredFields();
for (Field fields: f3) {
fields.setAccessible(true);
System.out.println(fields.get(person));
}
}
执行结果:
-----Class.getDeclaredField(String name)用法-------
VipMao
-----遍历属性值-------
VipMao
24
男
----修改name属性后再遍历属性值------
Maoge
24
男
总结
通过set(Object obj,value)重新设置新的属性值,并且当我们需要获取私有属性的属性值得时候,我们必须设置Accessible为true,然后才能获取。
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。