我有以下抽象类...
public abstract class IRepository<T> {
public T getEntityById(int idEntity){
try{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
T result = (T) session.createQuery( getByIdQuery() + idEntity ).uniqueResult();
tx.commit();
if (result != null){
System.out.println("Fetched " + result.toString());
return result;
}
else return null;
}
catch (Exception e){
// TO DO : logging
handleException(e);
return null;
}
}
还有另一个类,继承自这个类...
public class ProductRepository extends IRepository<Product> {
public ProductRepository(){
}
}
当我从主类执行以下调用时,出现错误...
ProductRepository prodRep = new ProductRepository();
Product result = prodRep.getEntityById(111);
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types
required: gestor.model.Product
found: java.lang.Object
我的问题是.. 为什么会这样?我的 getEntityById 不是返回类型 T 的东西吗,在这种情况下我应该是产品?
我在 Netbeans 中工作,编译时没有显示错误。
谢谢你的帮助=)
最佳答案
我怀疑您的导入或配置有误。在 Eclipse 中,您可以“清理”项目以清除所有二进制文件并重建;尝试 Netbeans 中的等效项。
下面的代码对我来说效果很好,它似乎是对你的问题的直接简化:
// Test.java
public abstract class Test<T> {
public T get(int i) {
return null;
}
public static void main(String[] args) {
StringTest st = new StringTest();
String s = st.get(0);
System.out.println(s); // prints: null
}
}
class StringTest extends Test<String> {
public StringTest() { }
}
关于Java泛型,不兼容类型错误(继承),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493362/