Java Reference
In-Depth Information
D.4. Code-generation strategies
A lambda expression is translated into bytecode by putting its body into one of a static method
created at runtime. A stateless lambda, one that captures no state from its enclosing scope, like
the one we defined in listing D.2 , is the simplest type of lambda to be translated. In this case the
compiler can generate a method having the same signature of the lambda expression, so the
result of this translation process can be logically seen as follows:
public class Lambda {
Function<Object, String> f = [dynamic invocation of lambda$1]
static String lambda$1(Object obj) {
return obj.toString();
}
}
The case of a lambda expression capturing final (or effectively final) local variables or fields, as
in the following example, is a bit more complex:
public class Lambda {
String header = "This is a ";
Function<Object, String> f = obj -> header + obj.toString();
}
In this case the signature of the generated method can't be the same as the lambda expression,
because it's necessary to add extra arguments to carry the additional state of the enclosed
context. The simplest solution to achieve this is to prepend the arguments of the lambda
expression with an additional argument for each of the captured variables, so the method
generated to implement the former lambda expression will be something like this:
public class Lambda {
String header = "This is a ";
Function<Object, String> f = [dynamic invocation of lambda$1]
static String lambda$1(String header, Object obj) {
return obj -> header + obj.toString();
}
}
 
Search WWH ::




Custom Search