【问题标题】:Generic captures [duplicate]通用捕获[重复]
【发布时间】: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;
    }
}

【问题讨论】:

  • 我通常不会在泛型中乱用?,但不是禁止在赋值右侧的泛型中使用? 吗? &lt;&gt; 隐含的运算符是哪个?
  • 更改后我无法在我的谓词中使用我的数据,因为它需要? super Serializable。由于我自己保持映射中的类型同步,我现在切换到 Predicate 和 TaggedData 的包装器对象列表。

标签: java generics wildcard predicate


【解决方案1】:

想象一下,您将Integer(即Serializable)传递给Predicate&lt;String&gt;(即extends Serializable)?这是毫无意义的。

Predicate#test() 充当消费者,因此您需要改用Predicate&lt;? super Serializable&gt;

阅读更多:What is PECS (Producer Extends Consumer Super)?

【讨论】:

  • 我选择了 T 数据,谓词
猜你喜欢
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
相关资源
最近更新 更多