方法引用指的是可以直接引用 Java 类或对象的方法。它可以被看成是一种更加简洁易懂的 Lambda 表达式,表达式如下所示:
Arrays.sort(people, Comparator.comparing(Person::getAge));
方法引用共有下面 4 种形式:
下面给出一个使用方法引用的例子,Java 代码如下:
import java.util.Arrays;
import java.util.Comparator;
import java.util.function.Supplier;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public static Person getInstance(final Supplier<Person> supplier) {
return supplier.get();
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public static int compareByAge(Person a, Person b) {
return b.age - a.age;
}
public String toString() {
return name + ":" + age;
}
}
class CompareProvider {
public int compareByAge(Person a, Person b) {
return a.getAge() - b.getAge();
}
}
public class Test {
public static void main(String[] args) {
//引用构造方法
Person p1 = Person.getInstance(Person::new);
p1.setAge(19);
System.out.println("测试引用构造方法:" + p1.getAge());
Person[] people = {new Person("James", 25), new Person("Jack", 21)};
//引用特定类的任意对象方法
Arrays.sort(people, Comparator.comparing(Person::getAge));
System.out.println("测试引用特定类的任意对象方法:");
for (Person p : people) {
System.out.println(p);
}
//引用类静态方法
Arrays.sort(people, Person::compareByAge);
System.out.println("测试引用类静态方法:");
for (Person p : people) {
System.out.println(p);
}
//引用某个对象的方法
Arrays.sort(people, new CompareProvider()::compareByAge);
System.out.println("测试引用某个对象的方法:");
for (Person p : people) {
System.out.println(p);
}
}
}
程序的运行结果为:
测试引用构造方法:19
测试引用特定类的任意对象方法:
Jack:21
James:25
测试引用类静态方法:
James:25
Jack:21
测试引用某个对象的方法:
Jack:21
James:25