问题:我在类中定义了一个Function Object接口:
public static interface FunctionObject<T> {
void process(T object);
}
Run Code Online (Sandbox Code Playgroud)
我需要它通用,因为我想在流程实现中使用T方法.
然后,在其他泛型类中,我有一个Map,其中我将类作为键,函数对象作为值:
Map<Class<T>, FunctionObject<T>> map;
Run Code Online (Sandbox Code Playgroud)
但我也希望地图接受子类型和超类型OF KEY TYPE的函数对象,所以我这样做:
Map<Class<? extends T>, FunctionObject<? super T>> map; //not what I need
Run Code Online (Sandbox Code Playgroud)
基本思路是能够如下使用地图:
//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>(){...});
Run Code Online (Sandbox Code Playgroud)
由于我想强制执行FunctionObject具有类键或超类型的类型,我真正想要定义的是:
Map<Class<E extends T>, FunctionObject<? super E>>> map;
Run Code Online (Sandbox Code Playgroud)
我怎样才能达到预期的效果?类型安全的异质容器是唯一的选择吗?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>() {});
}
}
Run Code Online (Sandbox Code Playgroud)
编辑以符合问题。遗憾的是,没有办法避免遭到反对。
编辑添加get()。
| 归档时间: |
|
| 查看次数: |
608 次 |
| 最近记录: |