Java 8 Method References

本文最后更新于 2024年4月17日 下午

Introduction

在 Java 8 中,方法引用是一种简化 Lambda 表达式的机制,它提供了一种更简洁的方式来调用已经存在的方法。方法引用可以看作是 Lambda 表达式的一种简写形式,用于直接引用已经存在的方法而不是提供一个匿名函数体。Java 8 通过::操作符来表示方法引用。

使用方法引用就是在引用的这个方法需要满足 lambda 表达式对应的函数式接口中的抽象方法的参数列表和返回值类型。

方法引用的类型

  • 静态方法引用:ClassName::methodName
  • 实例方法引用:object::methodName
  • 构造方法引用:ClassName::new

In Practice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Bound Method Reference
Consumer<String> print = System.out::println;
// Unbound Method Reference
Function<String, Integer> toLength = String::length;
BiFunction<String, String, Integer> indexOf = String::indexOf;
// Static Method Reference
IntBinaryOperator max = Math::max;
// Constructor Method Reference
Function<Integer, List<String>> newListOfNStrings = ArrayList::new;

public class Person {
String firstName;
String lastName;

public Person() {
}

public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

// setters and getters
}

@FunctionalInterface
public interface PersonFactory<T extends Person> {
T create(String firstName, String lastName);
}

PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Jane", "Doe");

Java 8 Method References
https://stein283036.github.io/2024/04/16/Java-8-Method-References/
作者
倪京龙
发布于
2024年4月16日
更新于
2024年4月17日
许可协议