public class Parent<T> {
}
public class Children<T> extends Parent<T> {
private Class<T> type;
public Class<T> getType() {
Type actualTypeArgument = ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
return (Class<T>) actualTypeArgument;
}
public static void main(String[] args) {
Children<String> children = new Children<>();
Class<String> type = children.getType();
System.out.println(type.getName());
}
}
想要获取泛型的Class,但是失败了:Exception in thread "main" java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
为什么Type强转Class失败了呢?
因为泛型擦除,所以只能拿到T拿不到具体类型(如果能拿到的话就太好了…
这种场景想拿到必须有个子类具体指定了T的类型,比如改成这样就能拿到了: