【发布时间】:2018-01-15 05:51:50
【问题描述】:
我已经声明了一个 Map,其中包含 Long 类型的键到嵌套 Map 的映射
嵌套映射具有 Class 类型的键和 SomeClient 类型的值 基本上我正在尝试生成类类型到产生类类型响应的客户端的映射。
private static final Map<Long, Map<Class<? super GenericResponse>, SomeClient<? super GenericResponse>>> someClientMap
= new HashMap<Long, Map<Class<? super GenericResponse>, SomeClient<? super GenericResponse>>>(); // <? super GenericResponse> should enable me to put subclasses of type GenericResponse in the Map
getSomeClient 方法是一个泛型方法,它接受类 Type 作为参数,并返回产生 Class Type 响应的客户端。(类类型只能是 GenericResponse 的子类:注意方法签名中的 Type 参数)
public static <T extends GenericResponse> SomeClient<T> getSomeClient(long clientId,Class<T> clazz) throws IOException {
if (someClientMap.get(clientId) == null) {
synchronized (someClientMap) {
someClientMap.put(clientId, new HashMap<Class<T>,SomeClient<T>>()); //getting error here
}
}
return someClientMap.get(clientId);
}
问题是我在尝试将客户端放入地图时遇到编译时错误。
确切的错误是
The method put(Long, Map<Class<? super GenericResponse>,SomeClient<? super GenericResponse>>) in the type Map<Long,Map<Class<? super GenericResponse>,SomeClient<? super GenericResponse>>> is not applicable for the arguments (long, HashMap<Class<T>,SomeClient<T>>)
我很难指出我到底做错了什么。请帮忙。
SomeClient 的声明是
public class SomeClient<T extends GenericResponse>
对于构造函数是
public SomeClient(Class<T> clazz)
【问题讨论】:
-
看起来问题出在
Longvslong- 你把long参数,地图期望Long。添加强制转换或使用Long.valueOf(.)方法 -
你能在问题中发布
SomeClient和GenericResponse的声明吗?
标签: java generics hashmap extends super