我有一个关于在容器中使用混合泛型类型的问题。Java泛型和混合类型的容器
我有这样的事情:
interface Processor<T> {
T process(T value);
}
class StringProcessor implements Processor<String> {
String process(String value);
}
然后我有一个使用的处理器的另一个参数类或接口。我希望确保我们设置成元素的处理器可以处理这种类型(T)的元素
class Element<T> {
<U> void setProcessor(U extends Processor<? extends T> processor);
}
所有这一切工作正常。当我必须将我的元素放入一个容器时,我的问题就来了。该容器可以包含不同类型的元素(Element<String>
,Element<Integer>
,...)。当我从容器中取出元素时,我无法为元素指定一个新的calcultor,因为使用?使我失去了打字。
List<Element<?>> container = new ArrayList<Element<?>>();
Element<String> strElement =new Element<String>();
strElement.setProcessor(new StringProcessor());
Element<Integer> intElement =new Element<Integer>();
intElement.setProcessor(new IntegerProcessor());
container.add(strElement);
container.add(intElement);
但是:
Element<?> e = container.get(0);
e.setProcessor(new StringProcessor()); // This does not compile because the the compiler is expecting a processor of type U extends Processor<#1of?> and not a StringProcessor.
这适用于Rawtypes但是你觉得有与泛型干净管理这个办法?
我已经从“Effective Java”中读取了模式,但是当我从容器中读取元素时,我无法预测返回类型是什么。
迄今为止发现的唯一修复方法是使Element不是通用的,但是通过这样做,我失去了类型安全性。
有什么想法欢迎?
问候
吉勒
你'Element'类没有编译。你能提供一个有效的实现吗? – 2014-11-23 11:44:28
你不能像你现在拥有它。通常的模式是在处理器上有一个'boolean canProcess(Object o)'方法。然后检查这个方法并强制演员。 – 2014-11-23 11:49:40