Saturday, July 24, 2010

Retrieving generic's Class type

Quite few times I've been using generic and I needed the Class type. I found out that I've to pass the class type instead of extracting the class type from the type parameter. This story comes to an end when I found out a way to extract the type, thanks to Type interface :)

Here's the recipe:
- First extract the genericSuperclass
- Retrieve the actual type arguments

.. and the code is:
ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
Class classType = (Class) type.getActualTypeArguments()[0];

ParameterizedType represents an invocation of a generic class or interface, better explanation could be read in the javadoc.

That's all... :)

No comments: