さまざまなタイプのデータのリストを返すメソッドを作成しようとしています。type 引数は、処理して getListedData(Class type) を返す必要があるデータのタイプを識別するためのものです。リストを作成するためにすべての型データで使用できるプライベート メソッド createList(Class type, List list, String flag) も作成しました。
コードは期待通りの動作をしていますが、ジェネリックスは初めてなので、これが最善の書き方であるとは確信が持てません。誰か私にいくつかの提案をしてもらえますか? 特に、ジェネリックを LIst および Reflect コンストラクターと共に使用してオブジェクト インスタンスを作成する場合。(私がこれを使用する理由は、メソッドをすべての型で再利用できるようにするためです)。そして、私はキャストにイライラします:(
これらの異なる型クラスは同じ構造になっています。
public class TypeA {
private String propOne;
public TypeA(String propOne) {
super();
this.propOne = propOne;
}
public String getPropOne() {
return propOne;
}
public void setPropOne(String propOne) {
this.propOne = propOne;
}
}
public class TypeB {
private String propOne;
public TypeB(String propOne) {
super();
this.propOne = propOne;
}
public String getPropOne() {
return propOne;
}
public void setPropOne(String propOne) {
this.propOne = propOne;
}
}
同じ構造化データ タイプが多数存在します。
public class Test {
@SuppressWarnings("unchecked")
public static void main(String arg[]) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException{
Test test = new Test();
List<TypeB> b = (List<TypeB>) test.getListedData(TypeB.class);
List<TypeA> a = (List<TypeA>) test.getListedData(TypeA.class);
//similar repeate.....
}
public <T> List<T> getListedData(Class<T> type) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
List<T> list = new ArrayList<T>();
String flag = "";
if(type.equals(TypeA.class)){
flag = "A";
createList(type, list, flag);
}else{
flag = "B";
createList(type, list, flag);
}
return list;
}
private <T> void createList(Class<T> type, List<T> list, String flag)
throws NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
for(int i=0; i<2; i++){
Constructor<?> ctor = type.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] {String.valueOf(i)});
list.add((T) object);
//do something with flag...
}
}
}
任意の提案をいただければ幸いです。ありがとう