本文主要描述一下什么是方法引用以及方法引用的四种表现形式
方法引用是Lambda表达式的一种语法糖
我们可以将方法引用看做是一个函数指针
-
方法引用共分为4类:
- 类名::静态方法名
- 对象名::实例方法名
- 类名::实例方法名
- 构造方法引用 类名:new
使用场景:Lambda表达式只有一行代码,并且有现成的可以替换
1. 类名::静态方法名:
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public static int compareStudentByScore(Student s1, Student s2) {
return s1.score - s2.score;
}
}
根据学生的分数进行排序
Lambda表达式的参数个数与类型正好和当前类的某个唯一方法需要的参数个数类型完全一致,此时可以用这种方法来替换Lambda表达式
Student s1 = new Student("zhangsan", 12);
Student s2 = new Student("lisi", 60);
Student s3 = new Student("wangwu", 40);
Student s4 = new Student("zhaoliu", 90);
List<Student> list = Arrays.asList(s1, s2, s3, s4);
//使用Lambda表达式的方式
list.sort((student1, student2) -> Student.compareStudentByScore(student1, student2));
/**
* 类名::静态方法名
*/
list.sort(Student::compareStudentByScore);
2. 对象名::实例方法名
public class StudentCompartor {
public int compareStudentByScore(Student s1, Student s2) {
return s1.getScore() - s2.getScore();
}
}
Lambda表达式的参数个数与类型正好和当前对象的某个唯一方法需要的参数个数类型完全一致,此时可以用这种方法来替换Lambda表达式
StudentCompartor studentCompartor = new StudentCompartor();
//Lambda表达式方式
list.sort((student1, student2) -> studentCompartor.compareStudentByScore(student1, student2));
/**
* 对象名::实例方法名
*/
list.sort(studentCompartor::compareStudentByScore);
3. 类名::实例方法名
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int compareByScore(Student student) {
return this.getScore() - student.getScore();
}
}
使用 类名::实例方法名 这种方式能够替换的Lambda表达式形式为:
Lambda表达式接收的第一个参数为当前类的对象,后面的参数依次为该对象中的某个方法接受的参数。此例中 Lambda表达式是(o1,o2)->o1.compareByScore(o2)
正好符合转换
//Lambda表达式方式
list.sort((o1,o2)->o1.compareByScore(o2));
/**
* 类名::实例方法名
*/
list.sort(Student::compareByScore);
4. 构造方法引用 类名:new
需要调用的构造器的参数列表需要与函数式接口中抽象方法的函数列表保持一致。
System.out.println("----------lambda表达式---------");
Supplier<Student> supplier = () -> new Student();
System.out.println(supplier.get());
System.out.println("-----------使用方法的引用----------");
Supplier<Student> supplier1 = Student::new;
System.out.println(supplier1.get());