Code:
@FunctionalInterface
interface VoidSupplier {
void apply() throws Exception;
}
void execute(VoidSupplier voidSupplier) {
if (voidSupplier != null) {
try {
voidSupplier.apply();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
Call execute
use lambda:
@Test
public void testLambda() {
InputStream i = null;
execute(() -> i.close()); // use lambda
System.out.println("output some message"); // will be executed
}
Call execute
use method reference:
@Test
void testMethodReference() {
InputStream i = null;
execute(i::close); // use method reference
System.out.println("output some message"); // will not be executed
}
When use lambda, execute(VoidSupplier)
will be executed first, and then execute () -> i.close()
.
but use method reference, i::close
will be executed first, and then execute execute(VoidSupplier)
.
Why lambda and method reference have different execution timing?