To get the generic types of a Class:
abstract class ClassWithGenericParameterType<ItemType> {
private Class<ItemType> itemType;
ClassWithGenericParameterType() {
ParameterizedType classType = (ParameterizedType) getClass().getGenericSuperclass();
Type[] types = classType.getActualTypeArguments();
itemType= (Class<ItemType>) types[0];
}
}
To make this work:
class ExtendingParameterizedGenericClass extends ClassWithGenericParameterType<String> {...}Thing is about this trick, is that the class you are analyzing must be abstract, and that a new Class would extend that abstract class specifying a valid Class as the Generic argument and not something like <ItemType2 extends Number>, this would result in getting Number.class!
No comments:
Post a Comment