Getting concrete java generic class used in sub classes

It is funny that you need to do wacky stuff like this in order to get the class of T used in subclasses when you make generics classes like <T extends SomClass>:

 private Class getGenericClass() 
 { 
  ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass();
  Class clazz = (Class) pt.getActualTypeArguments()[0]; 
  return clazz;
 }

What is even more funny is that the information is clearly stored in the classes at runtime, so why the wacky code to get hold of the concrete class used?

I know this information is not used to do rumtime type check and so on. But some time you need to get access the the type (class) declared in the generic sub classes. For instance if you want to load some data using JPA getEntityManager().find(someEntityClass, anId). Using T.class or some thing like that would be lovely instead of the wacky code above.

Kommentarer

Populære opslag fra denne blog

Classes in Seam 2 hot folder makes page load real slow

Code syntax highlighter in blogger blogspot