Unable to figure out behaviour : Method reference

2019-08-09 05:57发布

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.

2条回答
乱世女痞
2楼-- · 2019-08-09 06:13

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.

查看更多
Bombasti
3楼-- · 2019-08-09 06:18

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();
查看更多
登录 后发表回答