目录
方法引用是基于已存在的方法或构造函数,允许程序员通过引用来重用这些方法或构造函数的功能。方法引用可以看作是 Lambda 表达式的一个特殊形式,但它更简洁。
1 方法引用的类型
1.1 静态方法引用
ClassName::staticMethodName
示例代码:引用某个类的静态方法
import java.util.function.BiFunction;
public class Example {
public static int multiply(int x, int y) {
return x * y;
}
public static void main(String[] args) {
// 引用Example类的multiply方法
BiFunction<Integer, Integer, Integer> biFunction = Example::multiply;
int result = biFunction.apply(10, 20);
System.out.println(result); // 输出 200
}
}
1.2 实例方法引用
instanceReference::instanceMethodName
示例代码:引用某个实例对象的实例方法
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class Example {
public void print(Object obj) {
System.out.println(obj);
}
public static void main(String[] args) {
Example example = new Example();
// 引用example对象的print方法
Consumer<Object> consumer = example::print;
List<String> list = Arrays.asList("Hello", "World");
list.forEach(consumer);
// 输出 "Hello" 和 "World"
}
}
1.3 特定类型的实例方法引用
TypeName::methodName
示例代码:引用特定类型对象的所有实例方法
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static void main(String[] args) {
// 创建一个包含 Person 实例的列表
List<Person> people = new ArrayList<>(Arrays.asList(
new Person("Alice"),
new Person("Bob"),
new Person("Alice"),
new Person("Charlie")
));
// 使用特定类型的实例方法引用处理 Stream
List<String> names = people.stream()
.map(Person::getName) // 特定类型的实例方法引用
.distinct()
.collect(Collectors.toList());
// 打印结果
System.out.println(names); // 输出 [Alice, Bob, Charlie]
}
}
1.4 构造函数引用
ClassName::new
示例代码:引用某个类的构造函数
import java.util.function.BiFunction;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
// 使用构造函数引用创建 Person 对象
BiFunction<String, Integer, Person> personSupplier = Person::new;
// 创建 Person 对象
Person alice = personSupplier.apply("Alice", 30);
System.out.println(alice.getName() + " is " + alice.getAge() + " years old."); // 输出 "Alice is 30 years old."
}
}
2 方法引用的优势
简洁性:方法引用比 Lambda 表达式更简洁,减少了代码量。
可读性:方法引用通常更容易理解,因为它们直接指向现有的方法。
性能:在某些情况下,方法引用可能比 Lambda 表达式更高效,因为编译器可以直接调用现有的方法。