Bootstrap

java中双冒号运算符的使用


前言

java8中引入lambda表达式和函数式接口后,双冒号运算符成为了一种重要的功能。他可以将方法或构造函数作为参数传递,简化和提高了代码的可读性。
注意:双冒号运算符是用来替换lambda表达式的


一、用法格式

类名/对象名::方法名

二、静态方法引用

代码如下(示例):

public class Test {

    public static void printNum(int num){
        System.out.println(num);
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
        //foreach函数传递的lambda表达式
        //list.forEach(e->{printNum(e);});
        list.forEach(Test::printNum);
    }
}

foreach函数传递的是一个函数式接口
在这里插入图片描述
这里使用::语法对应的便是函数接口

三、实例方法引用

public class Student {

    public void getName(){
        System.out.println("张三");
    }

    public static void main(String[] args) {
        Student student = new Student();
        //获取实例化对象的方法,返回对象是一个Runnable函数式接口
        Runnable getName = student::getName;
        //调用run()运行
        getName.run();
    }
}

四、构造函数引用

在Supplier接口中实例化中,也是使用到了lambda表达式的方法:

Supplier<String> s = () -> "Hello World!"; 

所以它也可以使用方法引用的方式构造:

public class Student {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Supplier<Student> supplier = Student::new;
        Student student = supplier.get();
        student.setName("张三");
        System.out.println(student.getName());
    }
}


总结

其实双冒号语法的出现就是简洁lambda表达式的

;