我想要的是这样的:
public abstract Class Content {
private Map<Class<? extends Content>, List<? extends Content>> relations;
}
内容有一堆子类 - A、B、C、D 等...
最常见的用例是获得所有 A:
public List<A> getA() {
return (List<A>)relations.get(A.class);
}
还可以 - 除了丑陋的类型转换。
但真正的问题是没有什么能阻止我做一些愚蠢的事情,比如:
relations.put(A.class, List<B> myListOfBs);
所以调用上面的 getA() 会导致可怕的转换异常。有什么办法可以让编译器在上面的例子中警告我 - 并且不需要丑陋的转换。
谢谢
最佳答案
您可以围绕 Map
创建一个包装器并使用通用方法来约束您的 put 方法:
public class HeterogeneousContainer {
private final Map<Class<? extends Content>, List<? extends Content>> map;
public <T extends Content> void put(Class<T> type, List<T> values) {
map.put(type, values);
}
public <T extends Content> List<T> get(Class<T> type) {
//this warning can be safely suppressed after inspection
return (List<T>) map.get(type);
}
}
现在您知道只要容器的用户没有不当使用它(即以原始形式),那么键和值就必须对应...您不能调用 put(B.class , listOfAs);
.
关于Java Map,其中值是与键类型相同的值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059264/