Java 中的方法引用和構造器引用的差異?


方法引用類似於 lambda 表示式,用於引用一個方法,而不呼叫該方法,而構造器引用用於引用構造器,而不例項化指定的類。方法引用需要一個目標型別,類似於 lambda 表示式。但它們不是提供一個方法的實現,而是引用現有類或物件的一個方法,而構造器引用則為類內的不同構造器提供不同的名稱。

語法 - 方法引用

<Class-Name>::<instanceMethodName>

示例

import java.util.*;

public class MethodReferenceTest {
   public static void main(String[] args) {
      List<String> names = new ArrayList<String>();
      List<String> selectedNames = new ArrayList<String>();

      names.add("Adithya");
      names.add("Jai");
      names.add("Raja");
      names.forEach(selectedNames :: add); // instance method reference

      System.out.println("Selected Names:");
      selectedNames.forEach(System.out :: println);
   }
}

輸出

Selected Names:
Adithya
Jai
Raja


語法 - 構造器引用

<Class-Name>::new

示例

@FunctionalInterface
interface MyInterface {
   public Student get(String str);
}
class Student {
   private String str;
   public Student(String str) {
      this.str = str;
      System.out.println("The name of the student is: " + str);
   }
}
public class ConstrutorReferenceTest {
   public static void main(String[] args) {
      MyInterface constructorRef = Student :: new;   // constructor reference
      constructorRef.get("Adithya");
   }
}

輸出

The name of the student is: Adithya

更新日期: 2020 年 7 月 11 日

2K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.