3

我有以下抽象类...

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 工作,编译时没有显示错误。

谢谢你的帮助 =)

4

1 回答 1

3

我怀疑您的导入或配置中存在错误。在 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() { }
}
于 2013-05-11T03:14:31.303 回答