How lambda expressions work under the hood?
#java #java8 #lambda-expressions
How lambda expressions work under the hood?
It might look like the lambda expressions are just the syntax sugar for anonymous inner classes, but there is much more elegant approach. The simplest explanation is:
the lambda expression is represented by a new method, and it is invoked at run-time using invokedynamic.
Source code:
class LambdaExample {
public void abc() {
Runnable r = () -> {
System.out.println("hello");
}
r.run();
}
}
Bytecode equivalent:
class LambdaExample {
public void abc() {
Runnable r = <lambda$1 as Runnable instance>;
r.run();
}
static void lambda$1() {
System.out.println("hello");
}
}
Inside the JVM, there is a
lambda factory that creates an instance of the functional interface (e.g.
Runnable
) from the generated lambda method (e.g.
lambda$1
).