方法引用(Method References)是一种语法糖,它本质上就是 Lambda 表达式,我们知道Lambda表达式是函数式接口的实例,所以说方法引用也是函数式接口的实例。
Tips:什么是语法糖?语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。 可以将语法糖理解为汉语中的成语,用更简练的文字表达较复杂的含义。在得到广泛接受的情况下,可以提升交流的效率。
语法
方法引用使用一对冒号(::)来引用方法,格式如下:
类或对象 :: 方法名
eg
public class ConsumerMethodReference {public static void main(String[] args) {Consumer<String> c = s -> System.out.println(s);c.accept("Hello World");Consumer<String> consumer = System.out::println;consumer.accept("Hello World");}}
其中System.out就是PrintStream类的对象,println就是方法名。
方法引用的分类
方法引用的使用,通常可以分为以下 4 种情况:
- 对象 :: 非静态方法:对象引用非静态方法,即实例方法;
 - 类 :: 静态方法:类引用静态方法;
 - 类 :: 非静态方法:类引用非静态方法;
 - 
对象引用实例方法
public class ConsumerMethodReference {public static void main(String[] args) {Consumer<String> consumer = System.out::println;consumer.accept("Hello World");}}
类引用静态方法
public class ComparatorMethodReference {public static void main(String[] args) {// Lambda 表达式Comparator<Integer> l = (t1, t2) -> Integer.compare(t1, t2);System.out.println(l.compare(1, 2));// 类 :: 静态方法( compare() 为静态方法)Comparator<Integer> m = Integer::compare;System.out.println(m.compare(3, 2));}}
类引用实例方法
类引用构造方法
```java class Student { private String name;
public Student() {
System.out.println("Student无参数构造方法");
}
public Student(String name) {
System.out.println("Student单参数构造方法");this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
 
}
public class StructMethodReference {
    public static void main(String[] args) {
        // 使用 Lambda 表达式,调用无参构造方法
        Supplier
// 使用方法引用,引用无参构造方法Supplier<Student> b = Student::new;b.get();// 使用 Lambda 表达式,调用单参构造方法Function<String, Student> c = name -> new Student(name);Student s1 = c.apply("c");System.out.println(s1.getName());// 使用方法引用,引用单参构造方法Function<String, Student> d = Student::new;Student s2 = d.apply("d");System.out.println(s2.getName());}
} ```
