方法的引用

方法的引用

一、整体介绍

符号说明:双冒号为方法引用运算符,而它所在的表达式被称为方法引用
应用场景:如果Lambda表达式所要实现的方案,已经有其他方法存在相同的方案,那么则可以使用方法引用。常见的引用方式:
方法引用在IDK8中使用是相当灵活的,有以下几种形式:

1、instanceName:methodName对象::方法名

2、ClassName:staticMethodName类名::静态方法

3、ClassName::methodName类名::普通方法

4、lassNamenew类名::new调用的构造器

5、ypeName[]:new String::new调用数组的构造器

二、案例分析

案例中所用到的实体类位于文章最后方。

2.1对象名::方法名
    @Test
    public void test1(){
        Date date = new Date();
        Supplier<Long> supplier1=()->date.getTime();
        System.out.println(supplier1.get());
        Supplier<Long> supplier2=date::getTime;
        System.out.println(supplier2);
    }
    @Test
    public void test2(){
        User user = new User();
        user.setUsername("茴子白苗");
        Supplier supplier=user::getUsername;
        System.out.println(supplier.get());
    }

方法引用的注意事项:

1.被引用的方法,参数要和接口中的抽象方法的参数一样

2.当接口抽象方法有返回值时,被引用的方法也必须有返回值

2.2类名:静态方法名
    @Test
    public void test3(){
        Supplier<Long> supplier1=()->System.currentTimeMillis();
        System.out.println(supplier1.get());
        Supplier<Long> supplier2=System::currentTimeMillis;
        System.out.println(supplier2.get());
    }
2.3类名引用实例方法
    @Test
    public void test4() {
        Function<String, Integer> function1 = (s) -> s.length();
        Function<String, Integer> function2 = String::length;
        System.out.println(function1.apply("hello"));
        System.out.println(function2.apply("hello"));
    }
2.4类名:构造器
    @Data
    @AllArgsConstructor
    class Person {
        private Integer age;
        private String name;
    }

    @Test
    public void test5() {
        /*以下可以进行无参构造*/
        Supplier<User> supplier1 = () -> new User();
        Supplier<User> supplier2 = User::new;
        /*以下可以进行有参构造*/
        //lambda表达式        
        BiFunction<Integer,String,Person> biFunction1=(a,b)->new Person(a,b);
        Person person1 = biFunction1.apply(12, "茴子白苗");
        System.out.println(person1.toString());
        //方法引用        
        BiFunction<Integer,String,Person> biFunction2=Person::new;
        Person person2 = biFunction2.apply(13, "西红柿苗");
        System.out.println(person2);
    }
2.5数组::构造器
    @Test
    public void test6() {
        /*lambda表达式*/
        Function<Integer,String[]> function1=(a)->new String[a];
        System.out.println(function1.apply(5).length);
        /*方法引用*/
        Function<Integer,String[]> function2=String[]::new;
        System.out.println(function2.apply(8).length);
    }

三、附加

User对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String username;
    private String password;
    private String phoneNum;
    private String email;
    private Role role;
}
四、注意

进行练习时,添加Lombok插件,同时添加Lombok依赖。

        
            org.projectlombok
            lombok
            1.18.20
        
        
            junit
            junit
            4.13.2
        

你可能感兴趣的:(Java基础,lambda,java)