1. 构造器引用
1.1 格式:
类名 :: new
1.2 说明:
- 构造器引用在执行时,会调用指定的类的构造器,创建其对象。
- 具体调用的是哪个形参列表的构造器呢?取决于函数式接口的抽象方法的形参列表。此抽象方法的形参列表与
要调用的构造器的形参列表相同。 - 调用指定构造器后,创建的对象作为函数式接口的抽象方法的返回值。
//构造器引用
//Supplier中的T get()
@Test
public void test1(){
//1.
Supplier<Employee> sup1 = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
//2.
Supplier<Employee> sup2 = () -> new Employee();
//3.
Supplier<Employee> sup3 = Employee::new;
System.out.println(sup3.get());
}
//Function中的R apply(T t)
@Test
public void test2(){
//1.
Function<Integer,Employee> fun1 = new Function<Integer, Employee>() {
@Override
public Employee apply(Integer id) {
return new Employee(id);
}
};
//2.
Function<Integer,Employee> fun2 = Employee :: new;
System.out.println(fun2.apply(12));
}
//BiFunction中的R apply(T t,U u)
@Test
public void test3(){
BiFunction<Integer,String,Employee> fun1 = new BiFunction<Integer, String, Employee>() {
@Override
public Employee apply(Integer id, String name) {
return new Employee(id,name);
}
};
BiFunction<Integer,String,Employee> fun2 = Employee :: new;
}
2. 数组引用
格式: 数组元素类型[] :: new
//数组引用
//Function中的R apply(T t)
@Test
public void test4(){
//1.
Function<Integer,int[]> fun1 = new Function<Integer, int[]>() {
@Override
public int[] apply(Integer length) {
return new int[length];
}
};
//2.
Function<Integer,int[]> fun2 = int[] :: new;
int[] arr = fun2.apply(3);
for(int i : arr){
System.out.println(i);
}
}
标签:Function,Java,fun2,引用,数组,apply,Employee,new,public
From: https://blog.csdn.net/weixin_52828297/article/details/137285536