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

2014-11-24 03:19:38 · 作者: · 浏览: 12
fmt, "GenericParameterType", gpType[i]);

21 }

22 }

23 }

24 }

25 /* 输出结果如下(由于输出较长,这里只是给出有代表性的输出):

26 ... ...

27 public void java.util.ArrayList.add(int,E)

28 ReturnType: void

29 GenericReturnType: void

30 ParameterType: int

31 GenericParameterType: int

32 ParameterType: class java.lang.Object

33 GenericParameterType: E

34 ... ...

35 public T[] java.util.ArrayList.toArray(T[])

36 ReturnType: class [Ljava.lang.Object;

37 GenericReturnType: T[]

38 ParameterType: class [Ljava.lang.Object;

39 GenericParameterType: T[]

40 ... ...

41 */

4) 输出对象域字段的类型信息:

1 public class MyTest {

2 public String name = "Alice";

3 public List list;

4 public T val;

5

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

7 Class< > c = Class.forName("MyTest");

8 for (Field f : c.getFields()) {

9 //getType和getGenericType之间的差异和上面用到的

10 //getReturnType和getGenericReturnType之间的差别相同

11 System.out.format("Type: %s%n", f.getType());

12 System.out.format("GenericType: %s%n", f.getGenericType());

13 }

14 }

15 }

16 /* 输出结果如下:

17 Type: class java.lang.String

18 GenericType: class java.lang.String

19 Type: interface java.util.List

20 GenericType: java.util.List

21 Type: class java.lang.Object

22 GenericType: T

23 */

5. 枚举的反射:

1) 获取枚举的常量列表:

1 import static java.lang.System.out;

2 public class MyTest {

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

4 //判断该类是否为枚举

5 if (!Eon.class.isEnum())

6 return;

7 Class< > c = Eon.class;

8 out.format("Enum name: %s%nEnum constants: %s%n", c.getName(),

9 Arrays.asList(c.getEnumConstants()));

10 Eon[] vs = Eon.values();

11 for (Eon e : vs) {

12 out.println("The name is " + e.name() + "\tThe ordinal is " + e.ordinal());

13 }

14 }

15 }

16

17 enum Eon {

18 HADEAN, ARCHAEAN, PROTEROZOIC, PHANEROZOIC

19 }

20 /* 输出结果如下:

21 Enum name: Eon

22 Enum constants: [HADEAN, ARCHAEAN, PROTEROZOIC, PHANEROZOIC]

23 The name is HADEAN The ordinal is 0

24 The name is ARCHAEAN The ordinal is 1

25 The name is PROTEROZOIC The ordinal is 2

26 The name is PHANEROZOIC The ordinal is 3

27 */

6. 域方法的反射:

1) 通过类构造器的反射对象构造新实例:

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

2 //根据构造函数的参数列表获取Point类的带有该参数列表的构造函数的反射类

3 //该构造函数的原型为Point(int x,int y);

4 Constructor con = Point.class.getConstructor(new Class[] {

5 int.class, int.class });

6 //由于参数必须是Object的数组表示,因此对于Point构造的两个

7 //int参数,只能使用他们的包括类Integer.

8 Point obj = (Point) con.newInstance(new Object[] {

9