Using runtime generic type reflection to build a smarter DAO

Posted by kerry on Gooder Code See other posts from Gooder Code or by kerry
Published on Wed, 21 Jul 2010 14:52:55 +0000 Indexed on 2010/12/06 16:59 UTC
Read the original article Hit count: 293

Filed under:
|
|
|

Have you ever wished you could get the runtime type of your generic class? I wonder why they didn’t put this in the language. It is possible, however, with reflection:

Consider a data access object (DAO) (note: I had to use brackets b/c the arrows were messing with wordpress):

public interface Identifiable {

   public Long getId();

}

public interface Dao< T extends Identifiable > {

  public T findById(Long id);

  public void save(T obj);

  public void delete(T obj);

}

Using reflection, we can create a DAO implementation base class, HibernateDao, that will work for any object:


import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

public class HibernateDao< T extends Identifiable> implements Dao< T > {

  private final Class clazz;

  public HibernateDao(Session session) {
    // the magic
    ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
    return (Class) parameterizedType.getActualTypeArguments()[0];
  }

  public T findById(Long id) {
    return session.get(clazz, id);
  }

  public void save(T obj) {
    session.saveOrUpdate(obj);
  }

  public void delete(T obj) {
    session.delete(obj);
  }
}

Then, all we have to do is extend from the class:

public class BookDaoHibernateImpl extends HibernateDao< Book > {

}

© Gooder Code or respective owner

Related posts about Lessons

Related posts about generics