03. Java8-方法引用

x33g5p2x  于2021-12-18 转载在 其他  
字(2.1k)|赞(0)|评价(0)|浏览(315)

方法引用是Lambda 表达式的另一种简写方式. 普通的Lambda 表达式的lambda体其实就是一段匿名类的核心代码实现, 每次创建Lambda 表达式时都需要重新写一次方法的实现, 对于代码重用而言并不乐观. 而方法引用则时, 用已存在的函数的引用来创建lambda表达式, 只需要在一处编写方法实现体, 其它地方直接引用即可.

1. 方法引用格式

方法引用的前提是, 被引用的方法和函数式接口的抽象方法的方法签名完全一致!

1. 类对象::实例方法名

// 方法引用一: 类对象::实例方法
@Test
public void test_1(){

    //PrintStream 的实例方法println() 方法签名和Consumer 函数式接口抽象方法签名相同, 故可以使用方法引用
    PrintStream ps = System.out;
    Consumer<Object> consumer = (x) -> ps.println(x);
    consumer.accept("hello");

    // 使用方法引用方式
    Consumer<Object> consumer1 = ps::println;  // 等价于System.out::println
    consumer1.accept("world");
}

@Test
public void test_12(){
    Employee emp = new Employee(1001, "zhangsan", "Man", 20);

    // 实例对象的get 方法
    Supplier<String> nameSup = () -> emp.getName();
    String name = nameSup.get();
    System.out.println("name:" + name);

    System.out.println("---------------- 等价于 ------------------");

    // 实例对象的静态方法简写
    Supplier<Integer> ageSup = emp::getAge;
    Integer age = ageSup.get();
    System.out.println("age:" + age);
}

2. 类名::静态方法

// 方法引用二: 类实例:静态方法
@Test
public void test_2(){

    Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
    comparator.compare(10, 20);

    System.out.println("---------------- 等价于 ------------------");
    Comparator<Double> doubleComparator = (x, y) -> Double.compare(x, y);
    doubleComparator.compare(3.0, 5.0);
}

3. 类名:实例方法名

此种方式比较特殊, 目前只测试出两个参数这种情况. 第一个参数为方法的调用对象, 第二个参数为实例方法的参数.

// 方法引用三: 类名:实例方法
// 1. 实例方法和函数式接口方法名相同
// 2. 第一个参数是实例方法的调用对象, 第二参数为实例方法的参数
@Test
public void test_3(){
    BiPredicate<String, String> bi1 = (x, y) -> x.equals(y);
    boolean b = bi1.test("hello", "world");
    System.out.println(b);

    System.out.println("---------------- 等价于 ------------------");
    BiPredicate<String, String> bi2 = String::equals;
    boolean b2 = bi2.test("hello", "world");
    System.out.println(b2);
}

2. 构造器引用

构造器引用是方法引用的一种特殊情况, 构造器引用必须保证类中存在和函数式接口抽象方法参数个数相同的构造参数.

// 构造函数引用: 类中必须存在与函数式接口抽象方法中参数个数相同的构造器
@Test
public void test_4(){

    // 调用无参构造函数
    Supplier<Employee> supplier = Employee::new;
    System.out.println(supplier.get());

    // 调用有参构造函数
    Function<Integer, Employee> function = Employee::new;
    System.out.println(function.apply(1001));
}

相关文章