如何在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP