首页 > 其他 > 详细

方法引用

时间:2020-05-10 09:42:14      阅读:39      评论:0      收藏:0      [点我收藏+]

方法引用


public class Main {
    public static void main(String[] args) {
        //匿名内部类
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world!");
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
    }
}

需要使用函数式接口的对象的地方可以使用lambda表达式:

public static void main(String[] args) {
    //1.
    Runnable runnable = () -> {
        System.out.println("hello world!");
    };
    
    //2.
    Thread thread = new Thread(() -> {
        System.out.println("hello world!");
    });
    thread.start();
}

有时已经有现成的方法可以完成你想要传递给其他代码的某个动作,此时可以直接将该方法传递:

public class Main {
    public static void main(String[] args) {
        //1.
        Runnable runnable = Main::myRunnable;

        //2.
        Thread thread = new Thread(Main::myRunnable);
        thread.start();
    }

    //静态方法
    public static void myRunnable() {
        System.out.println("hello world!");
    }
}
public class Main {
    public static void main(String[] args) {
        //创建实例
        Main main = new Main();

        //1.
        Runnable runnable = main::myRunnable;

        //2.
        Thread thread = new Thread(main::myRunnable);
        thread.start();
    }

    //非静态方法
    public void myRunnable() {
        System.out.println("hello world!");
    }
}

方法引用

原文:https://www.cnblogs.com/KenBaiCaiDeMiao/p/12861484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!