Java のジェネリック クラスに問題があります。
私はこのクラスを持っています:
public abstract class MyMotherClass<C extends AbstractItem>
{
private C item;
public void setItem(C item)
{
this.item = item;
}
public C getItem()
{
return item;
}
}
このクラスの実装は次のとおりです。
public class MyChildClass extends MyMotherClass<ConcreteItem>
{
}
ConcreteItem は、AbstractItem (抽象) を拡張する単純なクラスです。
MyChildClass には ConcreteItem があり、次を使用できます。
MyChildClass child = new MyChildClass();
child.setItem(new ConcreteItem());
// automatic cast due to generic class
ConcreteItem item = child.getItem();
わかりました、今のところすべて問題ありません。問題は次のとおりです。
ここで、コレクションから MyMotherClass のインスタンスを抽出し、そのアイテムを設定します (タイプは不明です)。
Map<String, MyMotherClass> myCollection = new HashMap<String, MyMotherClass>();
Map<String, AbstractItem> myItems = new HashMap<String, AbstractItem>();
// fill the 2 collections
...
MyMotherClass child = myCollection.get("key");
child.setItem(myItems.get("key2"));
私がこのようにすれば、それは実行されます。しかし、 MyMotherClass はジェネリック型であり、ジェネリック型を使用していないため、警告があります。しかし、抽出した子のタイプがわからないので、ワイルドカードを使用したいと思います。
Map<String, MyMotherClass<?>> myCollection = new HashMap<String, MyMotherClass<?>>();
Map<String, AbstractItem> myItems = new HashMap<String, AbstractItem>();
// fill the 2 collections
...
MyMotherClass<?> child = myCollection.get("key");
child.setItem(myItems.get("key2"));
そして、ここに問題があります: 次のようなコンパイル エラーが発生しました: The method setItem(capture#1-of ?) in the type MyMotherClass is not applied for the arguments (AbstractItem)
継承されたワイルドカードを使用しようとすると、同じ問題が発生します:
Map<String, MyMotherClass<? extends AbstractItem>> myCollection = new HashMap<String, MyMotherClass<? extends AbstractItem>>();
Map<String, AbstractItem> myItems = new HashMap<String, AbstractItem>();
// fill the 2 collections
...
MyMotherClass<? extends AbstractItem> child = myCollection.get("key");
child.setItem(myItems.get("key2"));
私に何ができる ?
あまり流暢ではない私の英語に感謝し、申し訳ありません;)