Imagine I have an abstract class defining a Generic Type
. All subclasses will implement this Generic Type.
I can achive so by declaring a abstract method that forces the subclass to return that type. But is there a more elegant way to achieve this directly from the 'Class' object definition of the subclass?
public class GenericTest {
public static void main(String[]args) throws Exception{
Class strClass = ClazzImplString.class;
Class intClass = ClazzImplInteger.class;
Class implTypeStr = ((AbsClazz)strClass.getConstructor().newInstance()).getGenericType();
Class implTypeInt = ((AbsClazz)intClass.getConstructor().newInstance()).getGenericType();
System.out.println("implTypeStr: " + implTypeStr);
System.out.println("implTypeInt: " + implTypeInt);
}
}
abstract class AbsClazz<GenericType> {
abstract Class getGenericType();
}
class ClazzImplString extends AbsClazz<String> {
public ClazzImplString() {}
@Override Class getGenericType() {return String.class;}
}
class ClazzImplInteger extends AbsClazz<Integer> {
public ClazzImplInteger() {}
@Override Class getGenericType() {return Integer.class;}
}
Thank you in advance
Yes, you can use reflection.
ParameterizedType genericSuperclass = (ParameterizedType) ClazzImplString.class.getGenericSuperclass();
Class<?> clazz = (Class<?>) genericSuperclass.getActualTypeArguments()[0];
System.out.println(clazz); // prints class java.lang.String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With