方法引用与构造器引用
示例:
import cn.jsl.test.Employee;
import org.junit.jupiter.api.Test;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.*;
/**
* @author World
* @since 2021/7/21 16:14
*
* 一、方法引用:若Lambda体中的内容有方法已经实现了,五年可以使用“方法引用”
* (可以理解为方法引用式Lambda表达式的另一种表现形式
*
* 主要有三种语法:
* 1、对象::实例方法名
* 2、类::静态方法名
* 3、类::实例方法名
*
* 注意:
* 1、Lambda 体中调用方法的参数列表与返回值类型,
* 要与函数式接口中抽象方法的函数列表和返回值类型保持一致
* 2、如果 Lambda 参数列表中的第一参数是实例方法的调用者,
* 而第二个参数是实例方法的参数时,可以使用ClassName::method
*
* 二、构造器引用
* 格式:CLassName::new
*
* 注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致
*
* 三、数组引用
* Type::new
*
*/
public class MethodRefTest {
/**
* 对象::实例方法名
*/
@Test
public void test01(){
PrintStream ps1 = System.out;
Consumer<String > con = (x) -> ps1.println(x);
PrintStream ps = System.out;
Consumer<String> con1 = ps::println;
Consumer<String> con2 = System.out::println;
con2.accept("abc");
}
@Test
public void test02() {
Employee emp = new Employee();
Supplier<String> sup = () -> emp.getName();
String str = sup.get();
System.out.println(str);
Supplier<Integer> sup2 = emp::getAge;
Integer num = sup2.get();
System.out.println(num);
}
/**
* 类::静态方法名
*/
@Test
public void test03() {
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
Comparator<Integer> com1 = Integer::compare;
}
/**
* 类::实例方法名
*/
@Test
public void test04() {
BiPredicate<String,String> bq = (x,y) -> x.equals(y);
BiPredicate<String,String> bq2 = String :: equals;
}
/**
* 构造器引用
*/
@Test
public void test05(){
Supplier<Employee> sup = () -> new Employee();
//构造器引用方式
Supplier<Employee> sup2 = Employee::new;
Employee emp = sup2.get();
System.out.println(emp);
}
@Test
public void test06() {
Function<Integer,Employee> fun = (x) -> new Employee(x);
Function<Integer,Employee> fun2 = Employee::new;
Employee emp = fun2.apply(1);
System.out.println(emp);
BiFunction<Integer,Integer,Employee> bf = Employee::new;
}
/**
* 数组引用
*/
@Test
public void test07() {
Function<Integer,String[]> fun = (x) -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer,String[]> fun2 = String[]::new;
String[] strs2 = fun.apply(20);
System.out.println(strs2.length);
}
}
写test06()方法时需要在Employee中添加构造,代码如下:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private int id;
private String name;
private int age;
private double salary;
public Employee(Integer age){
this.age = age;
}
public Employee(Integer id,Integer age){
this.id = id;
this.age = age;
}
}