You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1.7 KiB
37 lines
1.7 KiB
import java.lang.reflect.*;
|
|
import java.util.*;
|
|
|
|
public class GenericReflectionDemo {
|
|
private Map<String, List<Integer>> complexField;
|
|
|
|
public List<Double> process(Map<String, ? extends Number> map, int value) {
|
|
return new ArrayList<>();
|
|
}
|
|
|
|
public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
|
|
Field field = GenericReflectionDemo.class.getDeclaredField("complexField");
|
|
Type genericType = field.getGenericType();
|
|
System.out.println("===== 字段泛型信息 =====");
|
|
if (genericType instanceof ParameterizedType) {
|
|
ParameterizedType pt = (ParameterizedType) genericType;
|
|
System.out.println("原始类型: " + pt.getRawType());
|
|
System.out.println("键的类型: " + pt.getActualTypeArguments()[0]);
|
|
System.out.println("值的类型: " + pt.getActualTypeArguments()[1]);
|
|
}
|
|
|
|
Method method = GenericReflectionDemo.class.getDeclaredMethod("process", Map.class, int.class);
|
|
Type returnType = method.getGenericReturnType();
|
|
System.out.println("\n===== 方法返回类型泛型 =====");
|
|
System.out.println("返回类型: " + returnType);
|
|
|
|
Type[] paramTypes = method.getGenericParameterTypes();
|
|
System.out.println("\n===== 方法参数泛型 =====");
|
|
for (Type param : paramTypes) {
|
|
System.out.println("参数类型: " + param);
|
|
if (param instanceof ParameterizedType) {
|
|
ParameterizedType ppt = (ParameterizedType) param;
|
|
System.out.println(" -> 实际类型参数: " + Arrays.toString(ppt.getActualTypeArguments()));
|
|
}
|
|
}
|
|
}
|
|
}
|