2010-11-22 75 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() 
}