【发布时间】:2015-10-21 15:21:10
【问题描述】:
我试图找出编译器抛出的原因
test(capture<? extends Serializable>) in Predicate cannot be applied to (Serializable)
test(e.getValue().getData()) 以及我该如何解决这个问题。
抛出编译器错误的代码如下
private Map<Predicate<? extends Serializable>, TaggedData<? extends Serializable>> scheduledData = new HashMap<>();
public synchronized <T extends Serializable> void conditionalSend(String tag, T data, Predicate<T> condition) {
scheduledData.put(condition, new TaggedData<T>(tag, data));
scheduledData.entrySet()
.stream()
.filter(e -> e.getKey().test(e.getValue().getData()))
.forEach(e -> send(e.getValue()));
}
我的 TaggedData 类是这样定义的
class TaggedData<T extends Serializable> implements Serializable {
private static final long serialVersionUID = 1469827769491692358L;
private final String tag;
private final T data;
TaggedData(String tag, T data) {
this.tag = tag;
this.data = data;
}
String getTag() {
return tag;
}
T getData() {
return data;
}
}
【问题讨论】:
-
我通常不会在泛型中乱用
?,但不是禁止在赋值右侧的泛型中使用?吗?<>隐含的运算符是哪个? -
更改后我无法在我的谓词中使用我的数据,因为它需要
? super Serializable。由于我自己保持映射中的类型同步,我现在切换到 Predicate 和 TaggedData 的包装器对象列表。
标签: java generics wildcard predicate