//获取泛型信息
public class GenericTest {
@SuppressWarnings("unused")
private Map<String,Integer> score;
@SuppressWarnings("unused")
private List<String> list;
public static void main(String[] args) throws Exception {
getGenericType("score");
getGenericType("list");
}
public static void getGenericType(String fieldName) throws Exception{
Class<GenericTest> clazz = GenericTest.class;
Field f = clazz.getDeclaredField(fieldName);
//直接使用getType()取出类型只对普通类型的成员变量有效
Class<?> a = f.getType();
System.out.println(fieldName+"的类型是:"+a);
//获取成员变量f的泛型类型
Type gType = f.getGenericType();
//类型判断
if(gType instanceof ParameterizedType){
//强制类型转换
ParameterizedType pType =(ParameterizedType)gType;
Type rType = pType.getRawType();
System.out.println("原始类型是:"+rType);
//取得泛型类型的泛型参数
Type[] tArgs = pType.getActualTypeArguments();
System.out.println("泛型的信息是:");
for (int i = 0; i < tArgs.length; i++) {
System.out.println("第"+i+"个泛型类型是:"+tArgs[i]);
}
}else{
System.out.println("获取泛型类型出错");
}
}
}
获取具体的泛型类型
最新推荐文章于 2024-01-04 14:55:37 发布