先看获取父类泛型参数
Type getGenericSuperclass() 获取带泛型参数的父类,返回值为Type类型
调用Type的子接口ParameterizedType的getActualTypeArguments()方法获取泛型参数的数组
简单看下Type接口:
Type接口
String getTypeName()返回Type的名字
子接口ParameterizedType
Type [] getActualTypeArguments()返回当前Type对象的所有参数
public class BaseDao<K, V> {
}
子类
public class EmployeeDao extends BaseDao<Employee,String>{
}
获取父类泛型参数
//根据子类Class对象和父类的泛型参数索引获取父类泛型参数
public Class getSuperClassGenericType(Class clazz,int index){
Type type = clazz.getGenericSuperclass();
if(!(type instanceof ParameterizedType)){
return null;
}
ParameterizedType paramType =(ParameterizedType) type;
Type [] args = paramType.getActualTypeArguments();
if(args == null ||index<0||index>args.length-1){
return null;
}
Type arg = args[index];
if(arg instanceof Class){
return (Class) arg;
}
return null;
}