[英]Parameterized class in Java
What am I doing wrong in this Java class? 在这个Java类中我做错了什么? clazz field is allways null.
clazz字段始终为空。 Shouldn't clazz be automatically populated with the type defined on the concrete class?
不应该用具体类中定义的类型自动填充clazz吗?
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
}
No, nothing in Java auto-populates a Class<T>
field in a generic class. 不,Java中没有任何内容会自动填充泛型类中的
Class<T>
字段。 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. 如果您的泛型类需要知道类型参数之一的类型,则必须添加
Class<T>
类型的构造函数参数,然后从那里对其进行初始化。 See, for example, the class EnumMap
in the JDK. 例如,请参见JDK中的
EnumMap
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.