/**
* 1. 构造器引用
* 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致
* 抽象方法的返回值类型即为构造器所属的类的类型
*
* 2. 数组引用
* 数组是一个特殊的类,写法与构造器引用一致
*/
public class ConstructorRefTest {
/**
* 构造器引用
* Supplier中的 T get()
* Employee的 空参构造器:Employee()
*/
@Test
public void test1(){
// Supplier<Employee> sup = () -> new Employee();
// System.out.println(sup.get());
Supplier<Employee> sup = Employee::new;
System.out.println(sup.get());
}
/**
* Function中的 R apply(T t)
*/
@Test
public void test2(){
// Function<Integer,Employee> func = id -> new Employee(id);
// Employee employee = func.apply(1001);
// System.out.println(employee);
Function<Integer,Employee> func = Employee :: new;
Employee employee = func.apply(1002);
System.out.println(employee);
}
/**
* BiFunction中的 R apply(T t,U u)
*/
@Test
public void test3(){
// BiFunction<Integer,String,Employee> func = (id,name) -> new Employee(id,name);
// System.out.println(func.apply(1001,"Tom"));
BiFunction<Integer,String,Employee> func = Employee::new;
System.out.println(func.apply(1002,"Tom"));
}
/**
* 数组引用
* Function中的 R apply(T t)
*/
@Test
public void test4(){
// Function<Integer,String[]> func = length -> new String[length];
// String[] arr = func.apply(5);
// System.out.println(Arrays.toString(arr));
Function<Integer,String[]> func = String[]::new;
String[] arr = func.apply(6);
System.out.println(Arrays.toString(arr));
}
}
javase:构造器引用
最新推荐文章于 2024-04-02 19:26:26 发布