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
}
3
  • You should be asking this question: stackoverflow.com/questions/18707582/… Commented Sep 18, 2015 at 20:18
  • Oops. I'm Sorry. Thanks btw. Commented Sep 18, 2015 at 20:20
  • wouldn't that be nice :) or if we could do E.class ... unfortunately we can't do that in java. Commented Sep 18, 2015 at 20:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What I meant by auto-populate was inferred from the concrete class. Issue solved with part of this: stackoverflow.com/a/18709327/1831948 Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.