问题
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