如何在超类构造函数中获取泛型类型的类?
换句话说,我想要一个Class<T>
实例,其中 T 是我的超类的泛型。这将在下面的代码中用于ChildA
我直接在类本身中定义泛型类的类,但是当子类是泛型类时,我也需要它来工作,例如GenericChildB
.
/**
* empty class
*/
private static class Foo{}
/**
* non generic class that extends from a generic class
*/
private static class ChildA extends GenericClass<Foo>{}
/**
* generic class that extends from a generic class
*/
private static class ClassChildB<T> extends GenericClass<T>{}
private abstract static class GenericClass<T> {
@SuppressWarnings("unchecked")
public GenericClass() {
Type type = getClass().getGenericSuperclass();
/**
* When constructed from ChildA:
* type = generics.Main$GenericClass<generics.Main$Foo>
* with other worlds the generic type
*
* But when constructed from GenericChildB:
* the generic type is just:
* type = generics.Main$GenericClass<T>
* and it throws an error when trying to cast his to an ParameterizedType
* because <T> is not an acctual class.
*
*/
System.out.println(type);
Class<T> classInstance = (Class<T>) ((ParameterizedType)type).getActualTypeArguments()[0];
//Goal is to get an Class<T> object inside of the constructor of GenericClass
System.out.println(classInstance);
}
}
public static void main(String[] args) {
//works :
GenericClass<Foo> genericClassA = new ChildA();
//does not work:
GenericClass<Foo> genericClassB = new GenericChildB<Foo>();
}