一、什麼是方法引用
- 方法引用通過方法的名字來指向一個方法。
- 方法引用可以使語言的結構更緊湊簡潔,減少冗餘代碼,能更加容易的看出我們的意圖。
- 方法引用使用一對冒號::
- 方法引用的返回值是函數式接口
二、方法引用的使用類型
方法引用主要有四種使用方式:
- 構造器引用
Class::new
- 靜態方法引用
Class::method
- 所有對象任意方法引用
Class:method
- 特定對象的方法引用
instance:method
三、使用示例
@Test
public void test1() {
//無參構造器
Supplier<Car> c = Car::new;
Car car = c.get();
System.out.println(car);
//帶參數的構造器
Function<String, Car> f = Car::new;
Car c2 = f.apply("寶馬");
System.out.println(c2);
}
@Test
public void test2() {
//靜態方法引用
Consumer<String> con = Car::showInfo;
con.accept("奔馳");
}
@Test
public void test3() {
//方法引用
Consumer<String> s = System.out::println;
s.accept("你好");
}
@Test
public void test4() {
List<String> names = new ArrayList<>();
names.add("Google");
names.add("Runoob");
names.add("Taobao");
names.add("Baidu");
names.add("Sina");
names.forEach(System.out::println);
}
測試結果如下:
Car [name=null, price=0]
Car [name=寶馬, price=0]
I am a Car, My name is 奔馳
你好
Google
Runoob
Taobao
Baidu
Sina