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.