1.构造器引用格式:
ClassName::new
2.构造器引用使用要求:
- 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
- 抽象方法的返回值类型即为构造器所属的类的类型
3.构造器引用举例:
//构造器引用
//Supplier中的T get()
//Employee的空参构造器:Employee()
@Test
public void test1(){
Supplier<Employee> sup = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
System.out.println(sup.get());
System.out.println("*******************");
Supplier<Employee> sup1 = () -> new Employee();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<Employee> sup2 = Employee :: new;
System.out.println(sup2.get());
System.out.println("*******************");
}
//Function中的R apply(T t)
//Employee的构造器:Employee(int id)
@Test
public void test2(){
Function<Integer,Employee> fun1 = id -> new Employee(id);
Employee e = fun1.apply(1001);
System.out.println(e);
System.out.println("********************");
Function<Integer,Employee> fun2 = Employee::new;
System.out.println(fun2.apply(1002));
}
//BiFunction中的R apply(T t,U u)
//Employee(int id, String name)
@Test
public void test3(){
BiFunction<Integer,String,Employee> bfun1 = (id,name) -> new Employee(id,name);
System.out.println(bfun1.apply(1001,"西西"));
System.out.println("***********************");
BiFunction<Integer,String,Employee> bfun2 = Employee::new;
System.out.println(bfun2.apply(1001,"西西"));
}
4.数组引用举例:
数组类型[] :: new
//数组引用
//Function中的R apply(T t)
//new String[int length];
@Test
public void test4(){
Function<Integer,String[]> fun1 = new Function<Integer, String[]>() {
@Override
public String[] apply(Integer length) {
return new String[length];
}
};
String[] fun1String = fun1.apply(5);
System.out.println(Arrays.toString(fun1String));
System.out.println("***********************");
Function<Integer,String[]> fun2 = length -> new String[length];
String[] fun2String = fun2.apply(5);
System.out.println(Arrays.toString(fun2String));
System.out.println("***********************");
Function<Integer,String[]> fun3 = String[] ::new;
String[] fun3String = fun3.apply(5);
System.out.println(Arrays.toString(fun3String));
}