Java类型推断失败: 不是功能界面

问题描述 投票:0回答:1

用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());
                        ^

显然,编译器无法推断出() -> action.run()的类型。

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

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

javac jls
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.