01 | package com.juziku; |
02 |
03 | /** |
04 | * 反射类 |
05 | * @author sunlightcs |
06 | * 2011-3-5 |
07 | * http://hi.juziku.com/sunlightcs/ |
08 | */ |
09 | public class ReflectPoint { |
10 | /** |
11 | * 私有变量x |
12 | */ |
13 | private int x; |
14 | |
15 | public int y; |
16 | public String str1 = "abc" ; |
17 | public String str2 = "123" ; |
18 | |
19 | public ReflectPoint( int x, int y) { |
20 | super (); |
21 | this .x = x; |
22 | this .y = y; |
23 | } |
24 | |
25 | } |
01 | package com.juziku; |
02 |
03 | import java.lang.reflect.Field; |
04 |
05 | /** |
06 | * 反射例子 |
07 | * @author sunlightcs |
08 | * 2011-3-5 |
09 | * http://hi.juziku.com/sunlightcs/ |
10 | */ |
11 | public class ReflectTest { |
12 |
13 | public static void main(String[] args) throws Exception{ |
14 | |
15 | ReflectPoint reflectPoint = new ReflectPoint( 3 , 5 ); |
16 | |
17 | /** |
18 | * 通过反射,获得ReflectPoint属性的值 |
19 | * |
20 | * reflectPoint.getClass()表示获得ReflectPoint的字节码, |
21 | * 当然也可以写成Field fieldY = ReflectPoint.class |
22 | * 或Class.forName("com.juziku.ReflectPoint"); |
23 | * 获得某个类的字节码的方法有3种: |
24 | * ReflectPoint.class (类名.class) |
25 | * reflectPoint.getClass() (对象名.getClass()) |
26 | * Class.forName("com.juziku.ReflectPoint") (Class.forName(类名的路径)) |
27 | * |
28 | * reflectPoint.getClass().getField("y")表示获得ReflectPoint里y属性的位置 |
29 | */ |
30 | Field fieldY = reflectPoint.getClass().getField( "y" ); |
31 | |
32 | /** |
33 | * fieldY.get(reflectPoint)表示获得reflectPoint对象里,y位置对应属性的值 |
34 | */ |
35 | Object y = (Object)fieldY.get(reflectPoint); |
36 | |
37 | /** |
38 | * 打印reflectPoint对象里,属于为y的值 |
39 | */ |
40 | System.out.println(y); |
41 | |
42 | |
43 | |
44 | /** |
45 | * 获得x属性的值,由于x属于为private类型, |
46 | * 所以要通过getDeclaredField方法查询x所在的位置 |
47 | */ |
48 | Field fieldX = reflectPoint.getClass().getDeclaredField( "x" ); |
49 | |
50 | /** |
51 | * 由于x属于为private类型,也要设置成可访问,不然获取不到值 |
52 | */ |
53 | fieldX.setAccessible( true ); |
54 | Object x = (Object)fieldX.get(reflectPoint); |
55 | System.out.println(x); |
56 | |
57 | |
58 | /** |
59 | * 获得类型为String的所有值 |
60 | */ |
61 | getStringValues(reflectPoint); |
62 | |
63 | |
64 | /** |
65 | * 修改str1属性的值 |
66 | */ |
67 | onchageValue(reflectPoint); |
68 |
69 | } |
70 |
71 | private static void getStringValues(Object obj) throws Exception{ |
72 | /** |
73 | * 获得所有属性的位置 |
74 | */ |
75 | Field[] fields = obj.getClass().getFields(); |
76 | |
77 | for (Field field : fields){ |
78 | /** |
79 | * 这里建议用==,不建议用equals |
80 | * 如果field属性是String类型的话,那么跟String的字节码是同一份 |
81 | */ |
82 | if (field.getType() == String. class ){ |
83 | String str = (String)field.get(obj); |
84 | System.out.println(str); |
85 | } |
86 | } |
87 | } |
88 |
89 | private static void onchageValue(Object obj) throws Exception{ |
90 | Field field = obj.getClass().getField( "str1" ); |
91 | System.out.println(field.get(obj)); |
92 | field.set(obj, "22" ); |
93 | System.out.println(field.get(obj)); |
94 | } |
95 |
96 | } |