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.

30 lines
1.2 KiB

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
public class GenericReflectDemo {
// 成员变量带泛型
private List<String> list;
public static void main(String[] args) throws NoSuchFieldException {
// 1. 获取成员变量的泛型类型
Field field = GenericReflectDemo.class.getDeclaredField("list");
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) genericType;
Type[] actualTypeArgs = pType.getActualTypeArguments();
for (Type arg : actualTypeArgs) {
System.out.println("泛型参数类型:" + arg); // 输出 class java.lang.String
}
}
// 2. 获取父类的泛型参数
class MyList extends ArrayList<String> {}
Type superType = MyList.class.getGenericSuperclass();
if (superType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) superType;
System.out.println("父类泛型参数:" + pType.getActualTypeArguments()[0]);
}
}
}