私はこの(簡略化された)Javaインターフェースを持っています
public interface MyInterface<T> {
public String run( T arg );
}
およびそのインターフェースを実装するいくつかのクラス、つまり
public final class SomeImplementation1 implements MyInterface<String> {
@Override
public String run( String arg) {
// do something with arg and return a string
}
}
と
public final class SomeImplementation2 implements MyInterface<CustomClass> {
@Override
public String run( CustomClass arg) {
// do something with arg and return a string
}
}
これで、これらすべての実装用のグローバル リソース マネージャーができました。これは、後で使用するためにそれらすべてを List でインスタンス化します。私が達成したいのはこのようなもので、明らかにエラーが発生します
public final class MyInterfaceManager {
private List<MyInterface<?>> elements = new List<MyInterface<?>>();
public MyInterfaceManager() {
elements.put( new SomeImplementation1() );
elements.put( new SomeImplementation2() );
// more implementations added
}
// this is what I would like to achieve
public <T> void run( T arg ) {
for( MyInterface<?> element: elements ) {
String res = element.run( arg ); // ERROR
}
}
}
「メソッド呼び出し変換で arg を ? の capture#1 に変換できない」ためです。考えられる解決策は、ループ内でテストを実行しinstanceof
、要素を引数とともに実際の型にキャストすることです。
public <T> void run( T arg ) {
for( MyInterface<T> element: elements ) {
if (element instanceof SomeImplementation2) {
String res = ((SomeImplementation2)element).run( (CustomClass)arg );
} else if // other tests here ...
}
}
しかし、私はそれが好きではありません。まったくエレガントではなく、多くのinstanceof
キャストを行う必要があります。だから、これを達成するためのより良い方法があるかどうか疑問に思っています。ご協力いただきありがとうございます :)