Java 范型编译时会进行类型擦除,运行期才决定具体类型,如果需要获取到运行期的范型实际 Type、Class 信息,可以通过 范型声明类的 Type 强转为 ParameterizedType 来获取类范型的实际类型;
假设有以下继承关系
public class P1 {
}
public class P2 extends P1 {
}
public class T1 {
}
运行时范型 Class,Type 信息获取代码
public class Param<T extends T1, P extends P1> {
public Param(){
Type type = getClass().getGenericSuperclass();
System.out.println("getClass() = " + getClass());
System.out.println("type = " + type);
//获取具体范型 Type
Type tType = ((ParameterizedType)type).getActualTypeArguments()[0];
Type pType = ((ParameterizedType)type).getActualTypeArguments()[1];
System.out.println("T type = " + tType);
System.out.println("P type = " + pType);
//获取具体范型 Class
System.out.println("(Class<T>)tType 's typeName = " + ((Class<T>)tType).getTypeName());
System.out.println("(Class<P>)pType 's typeName = " + ((Class<T>)pType).getTypeName());
}
}
测试代码
public class ParamChild extends Param<T1,P2>{
public static void main(String[] args) {
ParamChild param = new ParamChild();
}
}
/** output
getClass() = class reflect.reflect.ParamChild
type = reflect.reflect.Param<reflect.reflect.T1, reflect.reflect.P2>
T type = class reflect.reflect.T1
P type = class reflect.reflect.P2
(Class<T>)tType 's typeName = reflect.reflect.T1
(Class<P>)pType 's typeName = reflect.reflect.P2
*/