方法引用实际上是Lambda表达式的一种语法糖
可以将方法引用看作是一个【函数指针】,方法引用共分为4类: 1、类名::静态方法名
public class Student { private String name; private int score; //省略get,set和构造方法 //下面定义两个静态方法,分别根据分数和名字排序,后面用于方法引用 public static int compareByScore(Student s1,Student s2){ return s1.getScore() - s2.getScore(); } public static int compareByName(Student s1,Student s2){ return s1.getName().compareTo(s2.getName()); } } public class MyTest11 { public static void main(String[] args) { Student s1 = new Student("zhangsan",20); Student s2 = new Student("lisi",30); Student s3 = new Student("wangwu",40); Student s4 = new Student("zhaoliu",50); List<Student> list = Arrays.asList(s1,s2,s3,s4); //使用方法引用来调用Student中的方法排序,注意这里list.sort方法是传入一个Comparator参数,sort在1.8提供的,是一个函数式接口 list.sort(Student::compareByName); list.forEach(System.out::println); } }2、引用名、()::实例方法名
如果Student类中添加实例方法 public int compareInstance(Student s1,Student s2){ return s1.getScore() - s2.getScore(); } 则在调用排序方法时可以直接使用 list.sort(new Student(null,0)::compareInstance);//实例对象::实例方法3、类名::实例方法名
如果在Student类中添加实例方法 public int compareByInstanceName(Student student){ return this.getName().compareTo(student.getName()); } 则在调用排序方法时使用方式为: list.sort(Student::compareByInstanceName);//类::实例方法名 上述调用实际上等价于: list.sort((student1,student2) -> {return student1.compareByInstanceName(student2);});这种方式实际上是Lambda表达式中传递的第一个参数作为方法的调用者,而后面跟着的参数,不管是多少个,都作为第一个参数调用实例方法的参数。本例中排序方法只有两个参数,所以第二个参数将作为排序方法的时机参数。
4、构造方法引用,类名::new
定义两个方法: public String getString1(String test ,Function<String,String> function){ return function.apply(test) + "getString"; } public String getString2(Supplier<String> supplier){ return supplier.get() + "getString"; } 则调用形式可以使用: MyTest11 test = new MyTest11(); System.out.println(test.getString1("hahaha",String::new)); System.out.println(test.getString2(String::new));