Monday, November 7, 2011

Getting Java generic parameter types in runtime

For the long while I was using Java Generic types, in Methods, Fields and Classes, and I used to transfer the Class type instance as a parameter to the constructor or method respectively. Lately I've learned how Java's Generic types, can be determine in runtime.

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