无法弄清楚行为:使用lambda的方法引用 [英] Unable to figure out behaviour : Method reference with lambda

查看:139
本文介绍了无法弄清楚行为:使用lambda的方法引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码,

class DemoStatic {
    public static Runnable testStatic() {
        return () -> {
            System.out.println("Run");
        };
    }

    public void runTest () {
        Runnable r = DemoStatic::testStatic;
        r.run();
    }
}

public class MethodReferenceDemo {
    public static void main(String[] args) {
        DemoStatic demo = new DemoStatic();
        demo.runTest();
    }
}

run()方法 Runnable 正在返回的实例 testStatic 方法应该被调用。
控制台上的输出应该是运行。

run() method of Runnable instance that is being return by testStatic method was supposed to be invoked. And output on console should be "Run".

但是这段代码没有调用 run()实例的方法 r 并且没有任何内容在控制台中打印出来。

But this code is not invoking run() method of instance r and nothing is getting printed in console.

有人可以解释原因。

如果我没有正确使用方法参考::,请发表评论。

And comment if I am not using Method reference "::" properly.

推荐答案

要扩展Sotirios的回答:

To expand a bit on Sotirios' answer:

此声明:

Runnable r = DemoStatic::testStatic;

相当于

Runnable r = new Runnable() {
    @Override
    public void run() {
        DemoStatic.testStatic();
    }
}

所以 r.run( )调用一个调用 testStatic()的方法来返回 new Runnable ,但随后什么也没做。

So r.run() calls a method that calls testStatic() to return a new Runnable, but then does nothing with it.

这篇关于无法弄清楚行为:使用lambda的方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆