通过反射获取父类泛型的Class对象 ParameterizedType

((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]
这个方法这么用啊,返回什么,请给一个具体的例子

解释:

getClass().getGenericSuperclass()返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type

然后将其转换ParameterizedType。。

getActualTypeArguments()返回表示此类型实际类型参数的 Type 对象的数组。
[0]就是这个数组中第一个了。。

简而言之就是获得超类的泛型参数的实际类型。。

比如
超类
public class GenericDAO {
private Class entityClass;
protected GenericDAO() {
Type type = getClass().getGenericSuperclass();
Type trueType = ((ParameterizedType) type).getActualTypeArguments()[0];
this.entityClass = (Class) trueType;
}
}
子类
public class OptionManager extends GenericDAO<MSGC_OPTION> {

}
测试类
public class OracleTest {
public static void main(String[] args) throws Exception {
OptionManager manager = new OptionManager();
}
}
这样在你new OptionManager();以后
超类里的entityClass就是子类那里的public class OptionManager extends GenericDAO<MSGC_OPTION> 里面的MSGC_OPTION所对应的class对象了..

原文地址:https://www.cnblogs.com/jixu8/p/5907004.html