如何在Java中使用一个或多个参数实现构造函数引用
方法引用也可以适用于Java8中的构造函数。可以使用类名和new关键字创建构造函数引用。可以将构造函数引用分配给任何定义与该构造函数兼容的方法的功能接口引用。
语法
<Class-Name>::new
具有一个参数的构造函数引用示例
import java.util.function.*;
@FunctionalInterfaceinterface
MyFunctionalInterface {
Student getStudent(String name);
}
public class ConstructorReferenceTest1 {
public static void main(String[] args) {
MyFunctionalInterface mf = Student::new;
Function<Sttring, Student> f1 = Student::new; // 构造函数引用
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.*;
@FunctionalInterfaceinterface
MyFunctionalInterface {
Student getStudent(int id, String name);
}
public class ConstructorReferenceTest2 {
public static void main(String[] args) {
MyFunctionalInterface mf = Student::new; //构造函数引用
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