方法引用:

方法引用是Lambda表达式的一种简化写法,它使得我们可以直接引用已有方法或构造函数,而不用重新编写Lambda表达式。

方法引用的基本语法为:Class::methodNameobject::methodName

其中:

  • Class可以是类名,也可以是接口名;
  • methodName是方法的名称。

方法引用的类型包括:

  • 静态方法引用:Class::staticMethodName
  • 实例方法引用:object::instanceMethodName
  • 构造函数引用:Class::new
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.example.springbootdemo.jdk8.test1;

import java.util.function.Supplier;

/**
* 方法引用
* @author shuzhuoi
*/
class Main {

interface Converter {

int convert(String s);
}

static class Utility {
static int stringLength(String s) {
return s.length();
}


}

public static void main(String[] args) {
// 使用方法引用调用静态方法
Converter converter = Utility::stringLength;
// 其实就是
Converter converter2 = s-> Utility.stringLength(s);
// 因为传的参数是String类型,所以 Utility 类 调用 stringLength2 ,然后简写就是Utility::stringLength;
// 这种事静态方法引用


// 又因为是传了string ,所以可以直接用s 对象的方法
Converter converter3 = s-> s.length();
// 简写就是
Converter converter4 = String::length;
converter4.convert("123");
// 所以这种就是实例方法引用


// 构造函数引用
Supplier<Utility> supplier = Utility::new;
Utility utility = supplier.get();


}
}