Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Generic Hibernate dao

843793Feb 9 2009 — edited Apr 3 2009
Hi, I have been working with a generic HibernateDao to which I pass the entity type through a constructor parameter, and it works perfectly. I ran into a [SpringSource team blog|http://blog.springsource.com/2006/09/29/exploiting-generics-metadata/] by Rob Harrop that explained how to determine the actual type of the parameter at runtime. I also found a [page on the Hibernate documentation|http://www.hibernate.org/328.html] that explained the same concept. I used Robs version for my own GenericDao:
public class HibernateDao<E> implements GenericDao<E> {

    private SessionFactory sessionFactory;
    private Class<E> entityClass;

    public HibernateDao() {
        entityClass = extractTypeParameter(getClass());
    }

   // All sorts of DAO  methods 
   ...

   private Class extractTypeParameter(Class<? extends GenericDao> genericDaoType) {
        Type[] genericInterfaces = genericDaoType.getGenericInterfaces();
        // find the generic interface declaration for GenericDao<E>
        ParameterizedType genericInterface = null;
        for (Type t : genericInterfaces) {
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType)t;
                if (GenericDao.class.equals(pt.getRawType())) {
                    genericInterface = pt;
                    break;
                }
            }
        }
        if(genericInterface == null) {
            throw new IllegalArgumentException("Type '" + genericDaoType
               + "' does not implement GenericDao<E>.");
        }
        return (Class)genericInterface.getActualTypeArguments()[0];
    }
}
and ran into a ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class for the line with the return statement. It seems they both implement the Type interface, but they are no subclasses of each other. These articles must have been read and tried by numerous people and I found other sites that implement the same thing, what am I doing wrong to get this exception?

Edited by: Peetzore on 9-feb-2009 14:45

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 1 2009
Added on Feb 9 2009
4 comments
667 views