15 } else {
16 System.out.format(" -- No Type Parameters --%n%n");
17 }
18
19 System.out.format("Implemented Interfaces:%n");
20 //获取该类实现的接口,如果实现的接口为泛型接口,则打印出他的类型参数。
21 //getInterfaces()不会打印出类型参数。
22 Type[] intfs = c.getGenericInterfaces();
23 if (intfs.length != 0) {
24 for (Type intf : intfs)
25 System.out.format(" %s%n", intf.toString());
26 System.out.format("%n");
27 } else {
28 System.out.format(" -- No Implemented Interfaces --%n%n");
29 }
30 }
31 /* 输出结果如下:
32 Class:
33 java.util.ArrayList
34 Modifiers:
35 public
36 Type Parameters:
37 E
38 Implemented Interfaces:
39 java.util.List
40 interface java.util.RandomAccess
41 interface java.lang.Cloneable
42 interface java.io.Serializable
43 */
2) 获取类的泛型接口、接口、泛型超类和超类信息的比较:
1 public static void main(String args[]) throws Exception {
2 //1. 超类
3 Class< > ts = TreeMap.class.getSuperclass();
4 System.out.println(ts + "\n");
5 //2. 如果超类为泛型类,输出该泛型超类的类型信息。
6 Type t = TreeMap.class.getGenericSuperclass();
7 System.out.println(t + "\n");
8 //3. 接口
9 Class< >[] is = TreeMap.class.getInterfaces();
10 for (int i = 0; i < is.length; i++) {
11 System.out.println(is[i]);
12 }
13 System.out.println();
14 //2. 如果接口为泛型接口,输出该泛型接口的类型信息。
15 Type[] ts2 = TreeMap.class.getGenericInterfaces();
16 for (int i = 0; i < ts2.length; i++) {
17 System.out.println(ts2[i]);
18 }
19 }
20 /* 输出结果如下:
21 class java.util.AbstractMap
22
23 java.util.AbstractMap
24
25 interface java.util.NavigableMap
26 interface java.lang.Cloneable
27 interface java.io.Serializable
28
29 java.util.NavigableMap
30 interface java.lang.Cloneable
31 interface java.io.Serializable
32 */
3) 输出域方法的签名信息,包括返回值和参数列表的泛型类型信息:
1 import static java.lang.System.out;
2 public class MyTest {
3 private static final String fmt = "%24s: %s%n";
4 public static void main(String args[]) throws Exception {
5 Class< > c = Class.forName("java.util.ArrayList");
6 Method[] allMethods = c.getDeclaredMethods();
7 for (Method m : allMethods) {
8 //1. 获取域方法的完整描述,如果是泛型方法,则会给出类型信息
9 out.format("%s%n", m.toGenericString());
10 //2. 获取返回值类型
11 out.format(fmt, "ReturnType", m.getReturnType());
12 //3. 获取返回值类型,如为泛型类型,则打印出类型信息
13 out.format(fmt, "GenericReturnType", m.getGenericReturnType());
14 //4. 获取参数列表
15 Class< >[] pType = m.getParameterTypes();
16 //5. 获取参数列表,如为泛型参数,则打印出类型信息
17 Type[] gpType = m.getGenericParameterTypes();
18 for (int i = 0; i < pType.length; i++) {
19 out.format(fmt, "ParameterType", pType[i]);
20 out.format(