Step By Step(Java 反射篇) (五)

2014-11-24 03:19:38 · 作者: · 浏览: 4
段和所有声明的域字段(不包含超类的):

1 public class MyTest {

2 public static void main(String args[]) {

3 Class cls = java.awt.Point.class;

4 Field[] fieldPublic = cls.getFields();

5 System.out.println("Here are public fields.");

6 for (Field f : fieldPublic) {

7 System.out.println(f.getType());

8 }

9 Field[] fieldDeclared = cls.getDeclaredFields();

10 System.out.println("Here are all declared fields including private "

11 + "and static and protect.");

12 for (Field f : fieldDeclared) {

13 System.out.println(f.getType());

14 }

15 }

16 }

17 /* 输出结果如下:

18 Here are public fields.

19 int

20 int

21 Here are all declared fields including private and static and protect.

22 int

23 int

24 long

25 */

2) 基于域字段的字符串名称获取该域字段的值:

1 public class MyTest {

2 public static void main(String args[]) throws Exception {

3 Object o = new TestClass();

4 //根据域字段的字符串名字反射出与该字段对应Field类对象。

5 Field field = o.getClass().getField("firstValue");

6 //获取该域字段类型的Class对象。

7 Class< > type = field.getType();

8 //根据域字段的类型,调用Field.getXxx()方法获取该对象域字段的值。

9 if (type.toString().equals("double"))

10 System.out.println(field.getDouble(o));

11 else if (type.toString().equals("int"))

12 System.out.println(field.getInt(o));

13 }

14 }

15

16 class TestClass {

17 public double firstValue = 3.14;

18 }

19 /* 输出结果如下:

20 3.14

21 */

3) 获取和设置指定域字段的值:

1 public class MyTest {

2 public static void main(String args[]) throws Exception {

3 Bean demo = new Bean();

4 Class< extends Bean> cl = demo.getClass();

5

6 Field field = cl.getField("id");

7 field.set(demo, new Long(10));

8 Object value = field.get(demo);

9 System.out.println("Value = " + value);

10

11 field = cl.getField("now");

12 field.set(null, new Date());

13 value = field.get(null);

14 System.out.println("Value = " + value);

15 }

16 }

17 class Bean {

18 public static Date now;

19 public Long id;

20 public String name;

21 }

22 /* 输出结果如下:

23 Value = 10

24 Value = Sun Sep 04 11:38:15 CST 2011

25 */

4. 泛型信息的反射:

1) 获取类的泛型接口信息

1 public static void main(String args[]) throws Exception {

2 Class< > c = Class.forName("java.util.ArrayList");

3 System.out.format("Class:%n %s%n", c.getCanonicalName());

4 System.out.format("Modifiers:%n %s%n",

5 Modifier.toString(c.getModifiers()));

6

7 System.out.format("Type Parameters:%n");

8 //获取该泛型类的类型参数数组

9 TypeVariable[] tv = c.getTypeParameters();

10 if (tv.length != 0) {

11 System.out.format(" ");

12 for (TypeVariable t : tv)

13 System.out.format("%s ", t.getName());

14 S