vendredi 11 mars 2016

How to get actual type while type information is missing due to erasure [duplicate]

This question already has an answer here:

One way is to use

 this.entityClass = (Class<T>) ((ParameterizedType) getClass()
            .getGenericSuperclass()).getActualTypeArguments()[0];

But since the type information (in this case, entityClass is missing due to erasure), why I am still able to get right result? My confusion particularly lies on the method getActualTypeArguments, what is the mechanism behind this ?

Edit:

I am aware of the technique using anonymous subclass. However, This is not implemented in my project. To be more clear, the following is the whole class:

public abstract class BaseDao <T> {
    @Autowired
    private SessionFactory sessionFactory;

    private Class<T> entityClass;

    @SuppressWarnings("unchecked")
    public BaseDao()
    {
        this.entityClass = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public void save(Object o) {
        this.sessionFactory.getCurrentSession().save(o);
    }

    public void delete(Object o ) {
        this.sessionFactory.getCurrentSession().delete(o);
    }
    public List<T> findAll() {
        String queryString = "from " + entityClass.getName();
        Query query = this.sessionFactory.getCurrentSession().createQuery(queryString);
        return query.list();
    }
}

And the subclass :

@Repository
@Transactional(propagation = Propagation.MANDATORY)
public class AccountDao extends BaseDao<Account>{

}

Any thoughts are appreciated





Aucun commentaire:

Enregistrer un commentaire