![](/img/trans.png)
[英]Java Generics: How to specify a Class type for a generic typed class?
[英]In Java, how to specify generic type?
我正在嘗試創建一個定義搜索的通用方法。 搜索將接收字段名稱和要搜索的值作為輸入參數,而不是 object 本身。
問題是我在“返回”行中收到以下錯誤:
Multiple markers at this line
- Type safety: The method from(Class) belongs to the raw type AbstractQuery. References to generic type AbstractQuery<T> should be parameterized
- Type safety: The method where(Expression) belongs to the raw type CriteriaQuery. References to generic type CriteriaQuery<T> should be parameterized
- Illegal class literal for the type parameter T
- The method findOne(Example<S>) in the type QueryByExampleExecutor<T> is not applicable for the arguments (CriteriaQuery)
public abstract class ModelController<T extends HasId, R extends ModelRepository<T>> {
private T _findId(String field, String needle) {
EntityManager em;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
// Here I got the errors
return repository.findOne(cq.where(cb.equal(cq.from(T.class).get(field), needle)));
}
}
有什么線索嗎?
您的問題在於嘗試使用 T.class 訪問T
的T.class
。 Java 擦除 generics 的類型,您可以在他們的文檔中看到,因此獲得 class 參考的唯一方法是擴展您的方法以采用Class<T>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.