假设我有一个
HashMap<?, List<?>> map = new HashMap<>();
map.put(String.class, new ArrayList<Long>());
以下代码将编译。
但是,我想编译失败,因为 ArrayList 不是 String 类型。
另外,我的通配符仅限于某些特定的接口(interface)(例如异常),所以我想我应该把 <? extends Exception>
某处。
如何实现上述目标?
示例测试:
map.put(String.class, new ArrayList<String>()); //Fail because String is not an Exception
map.put(IOException.class, new ArrayList<FileNotFoundException>()); // Fail because FileNotFoundException is not an IOException even though it is a subclass of it
map.put(FileNotFoundException.class, new ArrayList<IOException>()); // I suppose I'm fine with this.
map.put(IllegalArgumentException.class, new ArrayList<IllegalArgumentException>()); // Succeed
map.put(NumberFormatException.class, new ArrayList<ServerException>()); // Fail again because the two classes don't match
map.put(ClientDecodingException.class, new ArrayList<ClientDecodingException.class>); // Succeed again since the map takes in a wildcard Exception
最佳答案
我相信您无法在声明时表达 map 键和值之间的通用约束。您可以将 map 声明为
Map<Class<Exception>, List<Exception>>
但是编译器不会知道列表中的异常必须扩展键的类。
我没有看到很多方法来确保检查此约束,除非使用诸如
之类的方法 <T extends Exception> void addToMap(Class<? extends T> aClass, List<T> aList) {
map.put(aClass, aList);
}
希望这有帮助。
关于java - Java 中的 "A Map of Class<?> to List<The class>"怎么说?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383942/