如何在 Java 中構建具有一個或更多引數的建構函式引用?


方法引用還可以適用於 Java 8 中的建構函式。可以使用 類名new關鍵字建立建構函式引用。可以將建構函式引用分配給定義與建構函式相容的方法的任何 函式式介面引用。

語法

<Class-Name>::new

帶一個引數的建構函式引用的示例

import java.util.function.*;

@FunctionalInterface
interface MyFunctionalInterface {
   Student getStudent(String name);
}
public class ConstructorReferenceTest1 {
   public static void main(String[] args) {
      MyFunctionalInterface mf = Student::new;

      Function<Sttring, Student> f1 = Student::new;    // Constructor Reference
      Function<String, Student> f2 = (name) -> new Student(name);

      System.out.println(mf.getStudent("Adithya").getName());
      System.out.println(f1.apply("Jai").getName());
      System.out.println(f2.apply("Jai").getName());
   }
}

// Student class
class Student {
   private String name;
   public Student(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

輸出

Adithya
Jai
Jai


帶兩個引數的建構函式引用的示例

import java.util.function.*;

@FunctionalInterface
interface MyFunctionalInterface {
   Student getStudent(int id, String name);
}
public class ConstructorReferenceTest2 {
   public static void main(String[] args) {
      MyFunctionalInterface mf = Student::new;    //  Constructor Reference

      BiFunction<Integer, String, Student> f1 = Student::new;
      BiFunction<Integer, String, Student> f2 = (id, name) -> new Student(id,name);

      System.out.println(mf.getStudent(101, "Adithya").getId());
      System.out.println(f1.apply(111, "Jai").getId());
      System.out.println(f2.apply(121, "Jai").getId());
   }
}

// Student class
class Student {
   private int id;
   private String name;
   public Student(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

輸出

101
111
121

更新於: 2020-7-14

8K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲取認證

開始
廣告