2010-11-22 7 views
2

オブジェクトのリストを返す次のJavaメソッドを書き直そうとしています。ドメインオブジェクトを一度書き込んでオブジェクトを渡すだけの汎用性があります。リフレクションを使用して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

を使用する代わりに、一般的な戻り値の型
B)E.modelとしてはそのような構築物はありませんを実装するために必要とされるa)は、あなたが必要となりますタイプ「クラス」のパラメータを追加します。 Eだけでは、タイプ消去のためにあなたを助けません。 –

+2

'E.model'は' E extends SomeClass'として 'E'が宣言され、' SomeClass'が公開 'model'属性を宣言しない限り動作しません。 –

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) –

2

Jinesh Parekh's answerですが、2つの詳細がありません。

クラスのparamaterはあなたがE.modelで取得したい場合clazz.getSimpleName()

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