gpt4 book ai didi

java - 编译器如何知道 lambda 正在实现哪个类?

转载 作者:行者123 更新时间:2023-12-01 19:34:09 27 4
gpt4 key购买 nike

我明白了 Thread() 两者都需要 RunnableString对于单参数构造函数。编译器如何知道 lambda正在实现 Runnable类而不是 String类?

    (new Thread( () -> {
System.out.println("Deleting stats...");
})).start();

也许它取决于类/接口(interface)中方法的数量?但是,如果一个类有多个构造函数,这些构造函数采用只有一个方法的单个参数类,例如:

Thread( Runnable r );
Thread( Comparable c );
Thread( ActionListener al );

当您尝试实现 lambda 时会发生什么然后?编译器如何知道 lambda 是哪个类正在实现吗?

最佳答案

Java 编译器必须为 lambda 表达式的类型选择函数接口(interface)类型。这是由 JLS, Section 15.27.3 管辖的,其中指出:

A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

String 类型不是函数式接口(interface)类型,但 Runnable 是。 lambda 不接受任何参数,也不返回任何数据,因此它与 Runnable 一致。

更一般地,lambda 表达式中的参数类型必须与函数接口(interface)类型的单个抽象方法的参数类型匹配,并且返回类型也必须匹配。

在您的示例中,3 种功能接口(interface)类型中的每一种都是不同的,因此最多有一种会匹配。如果有多个可能匹配的函数式接口(interface)类型,那么这将是不明确的,只能通过将 lambda 表达式转换为预期的函数式接口(interface)类型来解决。

关于java - 编译器如何知道 lambda 正在实现哪个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58457643/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com