What is a Java 8 Lambda Expression Compiled to? [duplicate]

The current draft of the Java 8 Language Specification states (chapter 15.27.4)

The value of a lambda expression is a reference to an instance of a
class with the following properties:

  • The class implements the targeted functional interface and, if the target type is an intersection type, every other interface element of the intersection.
  • The class declares a method that overrides the functional interface supertype’s abstract methods (and, potentially, some other methods of its superinterfaces).
  • The method’s parameter types, return type, and thrown types are given by the interface’s function type.
  • The method’s body has the effect of evaluating the lambda body, if it is an expression, or of executing the lambda body, if it is a
    block; if a result is expected, it is returned from the method.
  • The class overrides no other methods of the interface or interfaces mentioned above, except that it may override methods of the Object
    class.

Note that the JLS doesn’t say anything about how the code should be compiled except that the byte code should support the specification above.

As such, the object returned by the lambda expression

x -> System.out.print(x);  

will be an instance of a class that follows the above rules.

Given your comment that

consumer.getClass()

returns the following class

Example$$Lambda$1/1072591677

it seems that it is generating a proxy-like class specific for lambda expressions.

See here:

Leave a Comment