Accessing generic type info at runtime

I came across this problem when trying to create a generic data access layer supertype. I wanted an abstract DAO class that all my DAO’s would extend and automatically get the basic operations for free. One of the operations I wanted was a select query which I could add some basic sorting and paging to based on parameters passed in. To create the basic query I needed a way to get the table name, in theory this was available as a generic type argument but accessing it was a bit tricky…

This is what I came up with.

import org.springframework.core.GenericTypeResolver;
public abstract class AbstractHibernateDao<T extends DomainObject> implements DataAccessObject<T>
{
  @Autowired private SessionFactory sessionFactory;
  private final Class<T> genericType;
  private final String RECORD_COUNT_HQL;
  private final String FIND_ALL_HQL;
  public AbstractHibernateDao()
  {
    this.genericType = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), AbstractHibernateDao.class);
    this.RECORD_COUNT_HQL = "select count(*) from " + this.genericType.getName();
    this.FIND_ALL_HQL = "from " + this.genericType.getName() + " t ";
  }
....

Using springs GenericTypeResolver it was really easy to get the class name and generate the queries. This does of course assume that my domain objects have the same name as their tables. If you have more than one type argument e.g. <T extends DomainObject, PK extends PrimaryKey> then resolveTypeArguments can be used which returns Class[].

If you can’t use spring then it can also be done using plain Java.  Arjan explains this in his blog here:

http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/