目的: 必要なのは、さまざまなタイプのパラメーターを処理する関数を作成することList
です。関数内のリストを反復処理します。
試み:
1- 異なるタイプのリストを持つ複数の関数
public static int update(List<MyClass> myClasses){};
public static int update(List<Project> rojects){};
public static int update(List<Time> times){};
しかし、同じパラメータタイプを持つ複数の関数が原因で、コンパイルできないと見なされますList
。
2- 一般的なタイプのリスト、および ( instanceof
) の使用 しかし、方法がわからないため、これを完全に行うことはできませんでした。
私の質問: そのような要件を実装する Java の方法は何ですか? きれいなコードが必要です。複雑であっても気にしません。主に正確さと適切なコーディングに関心があります。
PS:instanceof
正しい方法であれば、リストをさまざまなタイプで反復処理する方法の小さな例を教えてください。
前もって感謝します :)
EDIT : 異なるオブジェクトは相互に関係がありません。相互に拡張したり、スーパークラスを拡張したりしません。各関数のブロックは、タイプごとに異なる SQLite ステートメントを生成しています。
'厳しい答え:
したがって、私はあなたの提案の組み合わせを使用することになりました。つまりgetClassType()
、クラス名の文字列を返す関数を使用して基本クラスを実装し、関数で返された値を確認しupdate(List<T> list)
ます。
public static <T extends Item> int update(List<T> list){
...
// Loop through the list and call the update function
for (T item: list){
if (item.getClassType() == MyClass.CLASS_TYPE)
update((MyClass) item);
}
...
}
public interface Item {
/**
* @return Return the class type, which is the name of the class
*/
public String getClassType();
}
public class ClassProject implements Item{
public static final String CLASS_TYPE = "ClassProject";
@Override
public String getClassType() {
return CLASS_TYPE;
}
...
}
public class ClassTime implements Item{
public static final String CLASS_TYPE = "ClassTime";
@Override
public String getClassType() {
return CLASS_TYPE;
}
...
}
public class MyClass implements Item{
public static final String CLASS_TYPE = "MyClass";
@Override
public String getClassType() {
return CLASS_TYPE;
}
...
}
これを全部作る理由interface
は、私はそれが好きistanceof
ではなく、パフォーマンスとコストについてもわからないため、自分で作成しようとしました。今、これはこれを行うひどい方法ですか?