2010-11-22 228 views
2

我试图重写下面的java方法,该方法返回一个对象列表(hibenrate域对象),使其更加通用,只需编写一次,并且能够将任何对象传递给它。使用反射重写java方法

public List<GsCountry> getCountry() { 
    Session session = hibernateUtil.getSessionFactory().openSession(); 
    Transaction tx = session.beginTransaction(); 
    tx.begin(); 
    List<GsCountry> countryList = new ArrayList<GsCountry>(); 
    Query query = session.createQuery("from GsCountry"); 
    countryList = (List<GsCountry>) query.list(); 
    return countryList; 
} 

我该怎么做才能自由地返回我作为参数传递的类型列表?

回答

2
//making the method name more generic 
public List<E> getData() { 
    Session session = hibernateUtil.getSessionFactory().openSession(); 
    Transaction tx = session.beginTransaction(); 
    tx.begin(); 
    List<E> result = new ArrayList<E>(); 

    // try to add a model final static field which could retrieve the 
    // correct value of the model. 
    Query query = session.createQuery("from " + E.model); 
    result = (List<E>) query.list(); 
    return result; 
} 
+2

,如果你想在E.model需要一个类paramater,您需要添加一个'Class '类型的参数。由于类型删除,单独E不会帮助你。 – 2010-11-22 07:48:45

+2

'E.model'不起作用,除非'E'被声明为'E extends SomeClass',其中'SomeClass'声明了一个公共'model'属性。 – 2010-11-22 07:49:03

2

这里是代码示例,从Don't repeat the DAO,你会发现有帮助。

public class GenericDaoHibernateImpl <T, PK extends Serializable> 
    implements GenericDao<T, PK>, FinderExecutor { 
    private Class<T> type; 

    public GenericDaoHibernateImpl(Class<T> type) { 
     this.type = type; 
    } 

    public PK create(T o) { 
     return (PK) getSession().save(o); 
    } 

    public T read(PK id) { 
     return (T) getSession().get(type, id); 
    } 

    public void update(T o) { 
     getSession().update(o); 
    } 

    public void delete(T o) { 
     getSession().delete(o); 
    } 

    // Not showing implementations of getSession() and setSessionFactory() 
} 
+0

当我看到这种模式不被使用时,我总是感到惊讶:-)(+1) – 2010-11-22 07:50:11

2

Jinesh Parekh's answer很好,但它缺少两个细节。

一)实施通用返回类型
二)有没有这样的结构为E.model,而是使用clazz.getSimpleName()

public List<E> getData(Class<E> clazz) { 
    // insert Jinesh Parekh's answer here 
    // but replace E.model with clazz.getSimpleName() 
}