import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
class MyClass {
}
class MyInvoke {
}
class Param<T1, T2> {
class A {
}
class B extends A {
}
private Class<T1> entityClass;
public Param() {
Type superClass = getClass().getGenericSuperclass();
System.out.println("当前类:" + getClass());
System.out.println("当前类的直接父类:" + superClass);
// getActualTypeArguments()返回表示此类型实际类型参数的Type对象的数组。[0]就是这个数组中第一个,也就是获得超类的泛型参数的实际类型。
Type trueType = ((ParameterizedType) superClass).getActualTypeArguments()[0];
System.out.println("超类的泛型参数的实际类型1 = " + trueType);
trueType = ((ParameterizedType) superClass).getActualTypeArguments()[1];
System.out.println("超类的泛型参数的实际类型2 = " + trueType);
this.entityClass = (Class<T1>) trueType;
System.out.println("entityClass = " + entityClass);
B t = new B();
// B的直接父类A
superClass = t.getClass().getGenericSuperclass();
System.out.println("B类的父类的泛型参数个数:" + ((ParameterizedType) superClass).getActualTypeArguments().length);
}
}
class ClassDemo extends Param<MyClass, MyInvoke> {
public static void main(String[] args) {
ClassDemo classDemo = new ClassDemo();
}
}