Unable to figure out behaviour : Method reference with lambda

心已入冬 提交于 2019-12-11 10:57:36

问题


Consider below code,

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() method of Runnable instance that is being return by testStatic method was supposed to be invoked. And output on console should be "Run".

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

Can some one please explain the reason.

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


回答1:


To expand a bit on Sotirios' answer:

This statement:

Runnable r = DemoStatic::testStatic;

is equivalent to

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

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




回答2:


This

Runnable r = DemoStatic::testStatic;

returns a Runnable whose run() method contains the body of the method testStatic(), ie.

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

so

r.run();

basically executes

return () -> {
    System.out.println("Run");
};

dropping the return value.

It's a static method reference. A method reference meaning your Runnable is referencing and executing the method in the method that functional interface defines.


For the behavior you want, you have to do

Runnable r = testStatic();


来源:https://stackoverflow.com/questions/23022939/unable-to-figure-out-behaviour-method-reference-with-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!