个人理解:构造器引用算是方法引用的一种特殊情况
格式如下:
- 格式: 类名::new
注意: 需要调用的构造器参数列表要与函数式接口中的参数列表保持一致!
@Test
public void Test1() {
Supplier<Student> supplier = () -> new Student(); //使用Lambda表达式
Supplier<Student> supplier1 = Student::new; //使用构造器引用
}
上面的构造器引用对应的是空参构造器 public Student() {}
@Test
public void Test2() {
Function<String, Student> function1 = (name) -> new Student(name); //使用Lambda表达式
Function<String, Student> function2 = Student::new; //使用构造器引用
System.out.println(function1.apply("Moti"));
System.out.println(function2.apply("Moti"));
BiFunction<String, Integer, Student> function3 = (name,age) -> new Student(name, age);//使用Lambda表达式
BiFunction<String, Integer, Student> function4 = Student::new; //使用构造器引用
System.out.println(function3.apply("Moti",20));
System.out.println(function4.apply("Moti",20));
}
以上方法中function1和function2对应的构造器是
public Student(String name) {
this.name = name;
}
而function3和function4对应的构造器是
public Student(String name, int age) {
this.name = name;
this.age = age;
}
留言