forked from aofeng/JavaTutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvokeField.java
More file actions
37 lines (29 loc) · 1.12 KB
/
InvokeField.java
File metadata and controls
37 lines (29 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package cn.aofeng.demo.java.lang.reflect;
import java.lang.reflect.Field;
import static cn.aofeng.demo.util.LogUtil.log;
/**
* 通过反射设置字段。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class InvokeField {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Man man = new Man();
Class<?> claz = man.getClass();
log("==========设置public字段的值==========");
log("height的值:%d", man.height);
Field field = claz.getField("height");
field.setInt(man, 175);
log("height的值:%d", man.height);
log("==========设置private字段的值==========");
log("power的值:%d", man.getPower());
field = claz.getDeclaredField("power");
field.setAccessible(true);
field.setInt(man, 100);
log("power的值:%d", man.getPower());
log("==========获取private字段的值==========");
int power = field.getInt(man);
log("power的值:%d", power);
}
}