How do I get a class instance of generic type T?

前端 未结 22 1251
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  鱼传尺愫
    2020-11-21 11:54

    I was looking for a way to do this myself without adding an extra dependency to the classpath. After some investigation I found that it is possible as long as you have a generic supertype. This was OK for me as I was working with a DAO layer with a generic layer supertype. If this fits your scenario then it's the neatest approach IMHO.

    Most generics use cases I've come across have some kind of generic supertype e.g. List for ArrayList or GenericDAO for DAO, etc.

    Pure Java solution

    The article Accessing generic types at runtime in Java explains how you can do it using pure Java.

    @SuppressWarnings("unchecked")
    public GenericJpaDao() {
      this.entityBeanType = ((Class) ((ParameterizedType) getClass()
          .getGenericSuperclass()).getActualTypeArguments()[0]);
    }
    

    Spring solution

    My project was using Spring which is even better as Spring has a handy utility method for finding the type. This is the best approach for me as it looks neatest. I guess if you weren't using Spring you could write your own utility method.

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

提交回复
热议问题