0

What am I doing wrong in this Java class? clazz field is allways null. Shouldn't clazz be automatically populated with the type defined on the concrete class?

Thanks!

public abstract class AbstractDAO<E extends Domain, T extends Number> {

    protected EntityManager em;
    private Class<E> clazz;

    public AbstractDAO(final EntityManager em) {
        this.em = em;
    }

    public E find(T id) {
        return em.find(clazz, id);
    }

    public List<E> findAll() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<E> cq = cb.createQuery(clazz);
        Root<E> from = cq.from(clazz);
        CriteriaQuery<E> select = cq.select(from);
        return em.createQuery(select).getResultList();
    }

    // other methods
}
Joao Brito
  • 23
  • 1
  • 9

1 Answers1

2

No, nothing in Java auto-populates a Class<T> field in a generic class. If your generic class needs to know the type of one of the type parameters, you must add a constructor argument of type Class<T> and initialize it from there. See, for example, the class EnumMap in the JDK.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • What I meant by auto-populate was inferred from the concrete class. Issue solved with part of this: http://stackoverflow.com/a/18709327/1831948 Thanks!! – Joao Brito Sep 18 '15 at 20:50