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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP