我有一个Java中的泛型类问题。
我有这个类:
这个类的一个实现可以是:
ConcreteItem只是一个简单的类,它扩展了抽象类AbstractItem。
因此,MyChildClass有一个ConcreteItem,我可以使用:
好的,目前一切都很好。这是问题:
现在我想从一个集合中提取MyMotherClass的实例并设置其项(其类型未知):
如果我这样做,它就能运行。 但是我收到了警告,因为MyMotherClass是一个泛型类型,而我没有使用泛型类型。 但是我不知道我的提取的子类是哪种类型,所以我想使用通配符:
这里的问题是:我遇到了一个编译错误,其内容为: 在MyMotherClass类中,方法setItem(capture#1-of ?)不适用于参数(AbstractItem)。
当我尝试使用继承的通配符时,仍然出现相同的问题。
我该做什么?
谢谢,对于我的英语不是很流利,很抱歉;)
我有这个类:
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"));
这里的问题是:我遇到了一个编译错误,其内容为: 在MyMotherClass类中,方法setItem(capture#1-of ?)不适用于参数(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"));
我该做什么?
谢谢,对于我的英语不是很流利,很抱歉;)
MyMotherClass#setItem()
更改为期望AbstractItem,并将MyMotherClass#getItem()
返回AbstractItem。然后更改MyChildClass
的相应方法 - 您的MyMotherClass的子类 - 以期望/返回正确的类。 - delfuego