-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericDemo.java
More file actions
44 lines (37 loc) · 1.18 KB
/
Copy pathGenericDemo.java
File metadata and controls
44 lines (37 loc) · 1.18 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
38
39
40
41
42
43
44
package FDynamic.Reflect;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.List;
public class GenericDemo {
static class GenericTest<U extends Comparable<U>, V> {
U u;
V v;
List<String> list;
public U test(List<? extends Number> numbers) {
return null;
}
}
public static void main(String[] args) throws Exception {
Class<?> cls = GenericTest.class;
// 类的类型参数
for (TypeVariable t : cls.getTypeParameters()) {
System.out.println(t.getName() + " extends " + Arrays.toString(t.getBounds()));
}
// 字段 - 泛型类型
Field fu = cls.getDeclaredField("u");
System.out.println(fu.getGenericType());
// 字段 - 参数化的类型
Field flist = cls.getDeclaredField("list");
Type listType = flist.getGenericType();
if (listType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) listType;
System.out.println("raw type: " + pType.getRawType() + ",type arguments:"
+ Arrays.toString(pType.getActualTypeArguments()));
}
// 方法的泛型参数
Method m = cls.getMethod("test", new Class[] { List.class });
for (Type t : m.getGenericParameterTypes()) {
System.out.println(t);
}
}
}