问题:我在类中定义了一个函数对象接口(interface):
public static interface FunctionObject<T> {
void process(T object);
}
我需要它是通用的,因为我想在流程实现中使用 T 方法。
然后,在其他通用类中,我有一个 Map,其中我将类作为键,将函数对象作为值:
Map<Class<T>, FunctionObject<T>> map;
但我也希望 map 接受 KEY TYPE 父类(super class)型的子类型类和函数对象,所以我这样做了:
Map<Class<? extends T>, FunctionObject<? super T>> map; //not what I need
基本思想是能够按如下方式使用 map :
//if T were Number, this should be legal
map.put(Class<Integer>, new FunctionObject<Integer>(){...});
map.put(Class<Float>, new FunctionObject<Number>(){...});
map.put(Class<Double>, new FunctionObject<Object>(){...});
因为我想强制 FunctionObject 具有类键的类型或父类(super class)型,所以我真正想定义的是:
Map<Class<E extends T>, FunctionObject<? super E>>> map;
怎样才能达到预期的效果?类型安全的异构容器是唯一的选择吗?允许从引用填充它的 Map 泛型类型是什么样的?
最佳答案
参数化容器,似乎工作得很好:
public class MyMap<T>
{
interface FunctionObject<X> {}
private Map<Class<? extends T>, FunctionObject<Object>> map = new HashMap<>();
@SuppressWarnings("unchecked")
public <E extends T> void put(Class<E> c, FunctionObject<? super E> f)
{
map.put(c, (FunctionObject<Object>) f);
}
public <E extends T> FunctionObject<Object> get(Class<E> c)
{
return map.get(c);
}
public static void Main(String[] args)
{
MyMap<Number> map = new MyMap<>();
map.put(Integer.class, new FunctionObject<Integer>() {});
map.put(Float.class, new FunctionObject<Number>() {});
map.put(Double.class, new FunctionObject<Object>() {});
}
}
编辑以符合问题。遗憾的是,没有办法避免对 object 的贬低。
编辑添加了get()
。
关于java - 泛型:如何在 Map 中强制执行键和值之间的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8848368/