Java 8 中有委托吗?

2022-01-18 00:00:00 lambda delegates java-8 java

Java 8 中有委托吗?

Are there delegates in Java 8?

如果没有,我们如何在 JDK 8 中使用 lambda 表达式没有委托?

If not, how do we have lambda expressions in JDK 8 without delegates?

什么是方法参考?他们和代表一样吗?

What are method references? Are they the same as delegates?

推荐答案

在 JDK 8 中没有委托.在底层 lambda 是函数式接口的实例(只有一个抽象方法的接口).根据您传递 lambda 的位置,编译器可以确定它正在实现的接口.例如 Collections.sort 方法接受一个 Comparator 实例作为第二个参数.Comparator 恰好是一个函数式接口,因此编译器将检查您传递的 lambda 是否与 Comparator 中的抽象方法匹配.

There are no delegates in JDK 8. Under the hood lambdas are instances of functional interfaces (an interface with exactly one abstract method). Depending on where you are passing your lambda the compiler can figure out what interface it is implementing. For example the Collections.sort method accepts a Comparator instance as a second parameter. The Comparator happens to be a functional interface so the compiler will check if the lambda you are passing matches the abstract method in Comparator or not.

方法引用只是一种简化.当您的 lambda 只是调用现有方法时,您可以使用这种新语法来简化构造.链接教程中的示例很好地展示了这一点:

A Method reference is just a simplification. When your lambda is just calling an existing method you can use this new syntax to simplify the construct. The example from the linked tutorial shows it pretty well:

代替:

Arrays.sort(rosterAsArray,
    (a, b) -> Person.compareByAge(a, b)
);

方法参考更简单:

Arrays.sort(rosterAsArray, Person::compareByAge);

看看 lambdafaq.

相关文章