Reputation: 43
I have been studying an example java code written by someone and faced the following snippet:
Runnable runnable = () -> System.out.println("Thread name: " + Thread.currentThread().getName());
Executor executor;
executor = Runnable::run;
executor.execute(runnable);
So, I can't figure out how method reference in this case makes it possible to instantiate an Executor and how is it possible to call execute(Runnable command)
if it was not implemented. In general how does the method reference works in this case behind the curtains?
Upvotes: 3
Views: 293
Reputation: 15684
An Executor
meets the definition of a functional interface, in that it has one abstract method. Namely this one:
void execute(Runnable command)
So what we need in order to implement this functional interface is a method which operates on a Runnable and returns nothing. command -> command.run()
, or Runnable::run
for short, is an example of a method that will do this.
The following three bits of code are equivalent:
executor = Runnable::run;
executor = (Runnable command) -> command.run();
executor = new Executor() {
public void execute(Runnable command) {
command.run();
}
}
Upvotes: 4