java中::的作用


::是java8的新特性,叫做方法引用

由于lamdba表达式中不可以直接执行方法,所以出现了方法引用

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        // 实例方法的方法引用
        ArrayList<String> list = new ArrayList();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        // list.forEach(path-> System.out.println(path)); 和下面的输出是一样的
        // 消费型函数式接口  path作为参数传递
        // 因为forEach要接收一个lambda表达式,所以要将method方法转换为方法引用
        list.forEach(new MethodQuote()::method1);
        System.out.println("=================这是一个分隔符=================");
        // 静态的方法引用
        list.forEach(MethodQuote::method2);
        System.out.println("=================这是一个分隔符=================");

    }

}

class MethodQuote{
     private String name;

    public MethodQuote() {
    }

    public MethodQuote(String name) {
        this.name = name;
    }

    public void method1(String path){
        System.out.println(path);
    }
    public static void method2(String path){
        System.out.println(path);
    }

    public static void main(String[] args) {
        // 类构造器引用语法 这里 并没有实现接口
        Interface methodQuote=MethodQuote::new;
        MethodQuote mq=methodQuote.create("java");
        System.out.println(mq.name);
    }

}

interface Interface{
    MethodQuote create(String name);
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM