getClass().getGenericSuperclass() problem
843793Aug 8 2009 — edited Sep 16 2009I read the hibernate article (https://www.hibernate.org/328.html) on how to use generic dao pattern. But whilst reading, one generic concept (I think) make me confused.
It subclasses the GenericDao<T, ID ...> interface with GenericHibernateDao abstract class, in which its constructor tries to obtain actual ParameteriedType (I think they are T and ID; so getActualTypeArguments()[0] is T).
However, when I practice to test if I am correct I notice that when doing casting, actually the getGenericSuperclass() returns Type that is the super class of ParameterizedType, which is what the page want to cast to.
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType)t;
As I understand, down casting is not permitted in Java. Therefore, this is why it goes wrong in runtime. In runtime, I obtained
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType.
So my question -
1.) is that statement
"this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];"
trying to obtain the Type (i.e., T) used in runtime?
2.) what is the right way to obtain T?
Thanks,