我有跟随着抽象类...Java泛型,不兼容类型的错误(与继承)
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工作,编译时没有显示错误。
感谢您的帮助=)
会发生什么,如果你尝试'IRepository prodRep =新ProductRepository()'? –
wchargin
2013-05-11 03:11:45
你可以试一下'Object result = prodRep.getEntityById(111);的System.out.println(结果);产品产品=(产品)结果;'? – wchargin 2013-05-11 03:21:43