方法引用:
方法引用是Lambda表达式的一种简化写法,它使得我们可以直接引用已有方法或构造函数,而不用重新编写Lambda表达式。
方法引用的基本语法为:Class::methodName
或 object::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;
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);
Converter converter3 = s-> s.length(); Converter converter4 = String::length; converter4.convert("123");
Supplier<Utility> supplier = Utility::new; Utility utility = supplier.get();
} }
|