Java 中的建構函式引用是什麼?


constructor reference 就如同一個方法 reference ,唯一的區別在於該方法的名稱為“new”。它可以使用“class name”和關鍵字“new”根據以下語法建立。

語法

<Class-Name> :: new

在以下示例中,我們使用 java.util.function.Function。它是一個函式式介面,其中唯一一個抽象方法是 apply()Function interface 代表一個接收單個引數 T 並返回結果 R 的操作。

示例

import java.util.function.*;

@FunctionalInterface
interface MyFunctionalInterface {
   Employee getEmployee(String name);
}
class Employee {
   private String name;
   public Employee(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
public class ConstructorReferenceTest {
   public static void main(String[] args) {
      MyFunctionalInterface mf = Employee :: new;   // constructor reference
      Function<String, Employee> f1 = Employee :: new;   // using Function interface
      Function<String, Employee> f2 = (name) -> new Employee(name);   // Lambda Expression

      System.out.println(mf.getEmployee("Raja").getName());
      System.out.println(f1.apply("Adithya").getName());
      System.out.println(f2.apply("Jaidev").getName());
   }
}

輸出

Raja
Adithya
Jaidev

更新於: 10-Jul-2020

237 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.