我有一个实用方法可以帮助ConcurrentMap.putIfAbsent
这样使用:
public static <K, V> V putIfAbsent(
ConcurrentMap<K, V> map, K key, Callable<V> task) {
try {
V result = map.get(key);
if (result == null) {
V value = task.call();
result = map.putIfAbsent(key, value);
if (result == null) {
result = value;
}
}
return result;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
现在我要处理这样一个异构的地图:
private ConcurrentMap<Class<?>, List<ClassHandler<?>>> handlerMap;
以及向其添加处理程序的方法:
public <T> void addHandler(Class<T> c, ClassHandler<? super T> handler) {
putIfAbsent(handlerMap, c, new Callable<List<ClassHandler<?>>>() {
@Override
public List<ClassHandler<?>> call() throws Exception {
return new CopyOnWriteArrayList<>();
}
}).add(handler);
}
到目前为止一切顺利,但是当我尝试处理课程时问题就来了,例如:
Class<String> c = String.class;
List<ClassHandler<?>> handlers = handlerMap.get(c);
if (handlers != null) {
for (ClassHandler<?> c : handlers) {
handler.handle(c);
}
}
但是,此代码无法编译:
error: method handle in class ClassHandler<T> cannot be applied to given types;
handler.handle(c);
required: Class<CAP#1>
found: Class<String>
reason: actual argument Class<String> cannot be converted to Class<CAP#1> by method invocation conversion
where T is a type-variable:
T extends Object declared in class ClassHandler
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
1 error
如果我使用handler.handle((Class) c)
,代码会编译,但我会收到未经检查的警告。虽然我可以添加@SuppressWarnings("unchecked")
注释,但如果没有更好的方法,这将是最后的选择。
对这个问题有任何想法吗?