如何在 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+ 次浏览

开启您的 职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.