用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指定的,还是这个编译器错误?
? super Runnable
的捕获代表了一种给定但未知的超级类型的Runnable
(可能是Object
)。要将类型分类为功能接口,您需要上限而不是下限。推断lambda的类型OTOH需要函数接口作为其目标类型。