java - Java 中的 "A Map of Class<?> to List<The class>"怎么说?

标签 java generics bounded-wildcard

假设我有一个

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/

相关文章:

java - 如何检测URL是否有文件?

Java:将 BigInteger 除以 3/Base 3 表示

c++ - 对给定结构成员应用操作的通用方法

HashMap 中的 Java 有界类型参数

java - 没有这样的bean异常

java - BitmapFactory.decodeByteArray() 返回 NULL

c# - 将类型的通用容器转换为继承类型的容器?

java - 泛型类到相同泛型类型的泛型数组

java - 为什么在函数式接口(interface)中使用下界

java - Bounded Type parameter (T extends) 和 Upper Bound Wildcard (? extends) 的区别