反射三(泛型)

泛型和反射:关键点是如何通过Class<T> 的到T对应的Clazz

(1)新建带泛型的父类例:Dao<T>

(2)  子类继承父类,并指定泛型的类型

public class PersonDao extends Dao<Person> {
    //具体代码省略
}

(3)  获取父类泛型参数具体Class

//获取子类Class
Class clazz = PersonDao.class;
//获取Dao子类带泛型参数的父类,即Dao<T>格式,T为具体类
Type type = clazz.getGenericSuperclass();
//获取具体泛型参数
if(type instanceof ParameterizedType){
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] args = parameterizedType.getActualTypeArguments();
if(args!=null && args.length>0){
Type arg = args[0];//获取泛型参数第一个参数,有时泛型的参数为多个
if(arg instanceof Class){
System.out.println("arg:"+arg);//得到父类泛型的Class
}
}
}
原文地址:https://www.cnblogs.com/yxqing/p/10605449.html