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/

Advertisements

4 thoughts on “Accessing generic type info at runtime

  1. public class RequestFactory
    {
    @SuppressWarnings(“unchecked”)
    public Class getGenericType()
    {
    return (Class) GenericTypeResolver.resolveTypeArgument(getClass(), RequestFactory.class);
    }
    I tried this one, but it returned an abstract Request class instead some specific child, any suggestions?

  2. First wrong, this one is correct

    public class RequestFactory
    {
    @SuppressWarnings(“unchecked”)
    public Class getGenericType()
    {
    return (Class) GenericTypeResolver.resolveTypeArgument(getClass(), RequestFactory.class);
    }
    I tried this one, but it returned an abstract Request class instead some specific child, any suggestions?
    Thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s