In Java 8 it looks like the lambdas of a class are kept in an array. For example, lets say we have this class:
public class LambdaFactory {
public Supplier<Integer> getOne(){
return () -> 42;
}
public Supplier<Integer> getTwo(){
return () -> 128;
}
public Supplier<Integer> getThree(){
return () -> 3;
}
}
and then I print it out like so:
System.out.println(factory.getOne());
System.out.println(factory.getOne());
System.out.println(factory.getTwo());
System.out.println(factory.getThree());
the output will be something like
examples.LambdaFactory$$Lambda$1@4e515669
examples.LambdaFactory$$Lambda$1@4e515669
examples.LambdaFactory$$Lambda$2@1b9e1916
examples.LambdaFactory$$Lambda$3@ba8a1dc
So we can see two thing here. The same lambda called twice gives us the same lambda object (this is not the same as with anon inner classes where we could get a new one every time). We also see that they look like they are being kept in some kind of "Lambda" structure that is part of the class
My question is, can I get ahold of the lambdas in a class? I don't have any reason to do so, I just like dissecting things
The Java Language Specification states
As such, it is up to a compiler or run time environment to decide what should be returned when a lambda expression is evaluated.
You can think of a lambda expression as any other class constant, a
String
, an integer literal, etc. These are constants that appear in the constant pool of a.class
file. These are references to objects that are created and exist at run time. There is no way to refer to the actual objects from a class' constant pool.In the case of a lambda, it wouldn't be helpful anyway because it might not actually be the same object.
The lambdas are created by the JRE and the way they are created is controlled by the JRE and might vary between different JRE vendors and might change in future versions.
If you want to have fun you can create a lambda at runtime which has no corresponding information within the class file:
The code above retraces what happens when a lambda is created. But for compile-time (“real”) lambda expressions the entire thing is triggered by a single
invokedynamic
byte code instruction. TheLambdaMetafactory.metafactory(…)
method is the bootstrap method which is called when theinvokedynamic
instruction is executed the first time. The returnedCallSite
object is permanently associated with theinvokedynamic
instruction. If theCallSite
is aConstantCallSite
and itsMethodHandle
returns the same lambda object on every execution, theinvokedynamic
instruction will “produce” the same lambda instance forever.