Java 8 引入方法引用(Method Reference),以 :: 操作符簡化 Lambda 表達式,提升代碼可讀性。本文系統梳理四種標準形式並給出典型場景代碼。
| 類型 | 語法 | 對應 Lambda | 適用場景 |
|---|---|---|---|
| 靜態方法引用 | ClassName::staticMethod | (args) -> ClassName.staticMethod(args) | 工具類、轉換函數 |
| 實例方法引用(特定對象) | instance::method | (args) -> instance.method(args) | 回調、事件處理 |
| 實例方法引用(任意對象/特定類型) | ClassName::method | (obj, args) -> obj.method(args) | 比較、排序、流式操作 |
| 構造方法引用 | ClassName::new | (args) -> new ClassName(args) | 工廠、集合轉換 |
@FunctionalInterface
interface FunStaticRef<P, R> {
R tranTest(P p);
}
public static void main(String[] args) {
// String.valueOf(Integer) -> FunStaticRef
FunStaticRef<Integer, String> ref = String::valueOf;
String str = ref.tranTest(10000); // "10000"
System.out.println(str.replaceAll("0", "9")); // "19999"
}
@FunctionalInterface
interface InstanRef<R> {
R upperCase();
}
public static void main(String[] args) {
String str2 = "i see you";
InstanRef<String> ref = str2::toUpperCase; // 綁定具體實例
System.out.println(ref.upperCase()); // "I SEE YOU"
}
@FunctionalInterface
interface SpecificMethodRef<P> {
int compare(P p1, P p2);
}
public static void main(String[] args) {
// String.compareTo(String) -> (s1, s2) -> s1.compareTo(s2)
SpecificMethodRef<String> ref = String::compareTo;
System.out.println(ref.compare("A", "B")); // -1
}
此處 String::compareTo 並非靜態方法,而是「第一個參數作為調用者」的實例方法引用。函數式接口第一個參數隱式對應調用者 this。
class Book {
private String title;
private double price;
public Book(String title, double price) {
this.title = title; this.price = price;
}
@Override public String toString() {
return "Book{title='" + title + "', price=" + price + "}";
}
}
@FunctionalInterface
interface ConstructorRef<T> {
T createObject(String title, double price);
}
public static void main(String[] args) {
ConstructorRef<Book> ref = Book::new;
Book book = ref.createObject("Java", 100.25);
System.out.println(book); // Book{title='Java', price=100.25}
}
編譯器根據目標類型(函數式接口簽名)推斷方法引用具體綁定哪個重載方法。若存在歧義,需顯式強轉或改用 Lambda。
list.forEach(System.out::println))。方法引用是 Lambda 的語法糖,四種形式覆蓋了靜態、實例、構造等常見調用模式。熟練掌握可顯著提升函數式編程代碼的表達力。