Java8學習筆記系列:
一、什麼是方法引用?
簡單來說就是一個Lambda表達式,方法引用提供了一種引用而不執行方法的方式,運行時,方法引用會創建一個函數式接口的實例。
如下所示:
@Test
public void example1(){
//使用Lambda表達式
Consumer<String> consumer1 = x -> System.out.println(x);
consumer1.accept("Lambda表達式");
//使用方法引用
Consumer<String> consumer2 = System.out::println;
consumer2.accept("方法引用::");
}
二、方法引用的五種方式
① 引用對象的實例方法 對象::實例方法名
② 引用類的靜態方法 類::靜態方法名
③ 引用類的實例方法 類::實例方法名
④ 引用構造方法 類::new
⑤ 數組引用 類型::new
使用示例如下:
/**
* 引用類
*/
class Human{
private String name;
private int age;
public Human(){ }
public Human(String name, int age) {
this.name = name;
this.age = age;
}
public static String getNationality(){
return "中國";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/**
* 引用對象的實例方法
*/
@Test
public void example3(){
Human human = new Human("小白",20);
//使用Lambda表達式
Supplier<String> supplier1 = () -> human.getName();
System.out.println(supplier1.get());
//使用方法引用
Supplier<String> supplier2 = human::getName;
System.out.println(supplier2.get());
}
/**
* 引用類的靜態方法
*/
@Test
public void example4(){
//使用Lambda表達式
Supplier<String> supplier1 = () -> Human.getNationality();
System.out.println(supplier1.get());
//使用方法引用
Supplier<String> supplier2 = Human::getNationality;
System.out.println(supplier2.get());
}
/**
* 引用類的實例方法名
*/
@Test
public void example5(){
Human human = new Human("小白",20);
//使用Lambda表達式
Function<Human, String> function1 = p -> p.getName();
System.out.println(function1.apply(human));
//使用方法引用
Function<Human, String> function2 = Human::getName;
System.out.println(function2.apply(human));
}
/**
* 引用構造方法
*/
@Test
public void example6(){
//使用Lambda表達式
Supplier<Human> supplier1 = () -> new Human();
System.out.println(supplier1.get() instanceof Human); //true
//使用方法引用
Supplier<Human> supplier2 = Human::new;
System.out.println(supplier2.get() instanceof Human); //true
}
/**
* 引用數組
*/
@Test
public void example7(){
//使用Lambda表達式
Function<Integer, String[]> function1 = x -> new String[]{x.toString()};
System.out.println(function1.apply(10) instanceof String[]); //true
//使用方法引用
Function<Integer, String[]> function2 = String[]::new;
System.out.println(function2.apply(10) instanceof String[]); //true
}
參考: