I'm trying to use Java 8 lambdas and have a general question about object serialization. For example the following input prints 5 if the executor.execute has only one method and runs the code block without serializing it. However if I serialize the lambda expression via SerializedLambda and deserialize it back, it prints null since it doesn't have the previous context in this new deserialized object. Moreover, it compiles without any complaint since the first context resolves outside variables. (finalVar in this example):
final int finalVar = 5;
executor.execute(() -> {
System.out.println(finalVar);
});
I wonder whether it's possible to tell the SerializedLambda to include finalVar into serialization output without implementing an interface that has a field for finalVar variable and set the value of it to a field when constructing. AFAIK, this is the cleanest way to do such thing in Java:
final int finalVar = 5;
executor.execute(new Runnable() {
int myVar = finalVar;
public void run() {
System.out.println(myVar);
}
);
I'm not even sure about that but I think the compiler can find out the outside variables and also serialize and include them when I try to serialize that lambda. Is there any trick for Java to do such thing or is there any language that has such feature?