2015-05-21 20 views
1

说我有一个如何在Java中说“地图类<?>到列表<The class>”?

HashMap<?, List<?>> map = new HashMap<>(); 
map.put(String.class, new ArrayList<Long>()); 

将下面的代码编译。

不过,我想是因为ArrayList的不是字符串类型失败编译。

而且,我的通配符仅限于一些特定的接口(例如例外),所以我想我应该把那<? 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 
+0

什么'地图,列表>'? –

+0

不能做到:( – yshavit

+0

@LuiggiMendoza这将需要''要声明的地方,然后你的地图只能包含类型的类/名单 - 你不能同时拥有T =字符串和T = IOException异常 – yshavit

回答

1

我beleive你不能表达对申报地图的键和值之间的这种通用约束。您可以将地图声明为

Map<Class<Exception>, List<Exception>> 

但是然后编译器不会知道列表中的异常必须扩展该键的类。

我没有看到很多的确保此约束的方式进行检查,除非使用方法如

<T extends Exception> void addToMap(Class<? extends T> aClass, List<T> aList) { 
     map.put(aClass, aList); 
    } 

希望这有助于。

public class ExceptionMapWrapper { 

    private Map<Class, List> myMap; 

    public ExceptionMapWrapper() { 
     myMap = new HashMap<>(); 
    } 
    //relevant methods for the test: put and get 
    public <T extends Exception> void put(Class<T> clazz, List<T> list) { 
     myMap.put(clazz, list); 
    } 

    public <T extends Exception> List<T> get(Class<T> key) { 
     return myMap.get(key); 
    } 
} 

和一个简单的测试此:

1

我已经使用原始ClassList(仍不能修复这一点),并通过使用地图的包装,仅用来存储Exception做到了这一点

ExceptionMapWrapper exceptionMapWrapper = new ExceptionMapWrapper(); 
Class<IOException> clazz = IOException.class; 
List<IOException> list = new ArrayList<>(); 
exceptionMapWrapper.put(clazz, list); 
//compiler errors, uncomment to see them 
//exceptionMapWrapper.put(String.class, new ArrayList<String>()); 
//exceptionMapWrapper.put(IOException.class, new ArrayList<ClassCastException>()); 
//exceptionMapWrapper.put(IOException.class, new ArrayList<SQLException>()); 
List<IOException> ioExList = exceptionMapWrapper.get(clazz); 
//compiler error, uncomment to see 
//List<SQLException> sqlExList = exceptionMapWrapper.get(clazz); 
相关问题