【问题标题】:Java type inference fails: <captured wildcard> is not a functional interfaceJava 类型推断失败:<captured wildcard> 不是功能接口
【发布时间】:2019-03-21 16:31:46
【问题描述】:

使用 java 8 编译器,这个程序:

import java.util.function.Consumer;
public class xx {
    public void execute(Consumer<? super Runnable> executor, Runnable action) {
        executor.accept(() -> action.run());
    }
}

失败:

xx.java:4: error: incompatible types: <captured wildcard> is not a functional interface
        executor.accept(() -> action.run());
                        ^

显然编译器无法推断() -&gt; action.run()的类型。

通过将 ? super Runnable 更改为 Runnable 或将 lambda 显式转换为 Runnable,这很容易解决。

我的问题:这个失败似乎有点“愚蠢”.. 这种行为是由 JLS 指定的,还是编译器错误?

【问题讨论】:

    标签: javac jls


    【解决方案1】:

    捕获? super Runnable 表示给定但未知的超类型Runnable(可能是Object)。要将类型分类为功能接口,您需要一个上限,而不是下限。推断 lambda 的类型 OTOH 需要函数接口作为其目标类型。

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      相关资源
      最近更新 更多