Enabling external variables when serializing an object

I am trying to use Java 8 lambdas and ask a general question about serializing objects. For example, the following input prints 5 if executor.execute has only one method and runs a block of code without serializing it. However, if I serialize a lambda expression through SerializedLambda and deserialize it back, it prints zero, since it does not have the previous context in this new deserialized object. Moreover, it compiles without any complaints, since the first context allows external variables. (finalVar in this example):

final int finalVar = 5; executor.execute(() -> { System.out.println(finalVar); }); 

I wonder if SerializedLambda can include finalVar in serialization output without implementing an interface that has a field for the finalVar variable and set its value to the field when constructing. AFAIK, this is the cleanest way to do this 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 this, but I think the compiler can recognize external variables, as well as serialize and enable them when I try to serialize this lambda. Is there any trick for Java to do such a thing, or is there any language that has such a function?

+6
source share
1 answer

Regardless of the scope variable, serial lambdas will include external variables if the types of these variables are Serializable . Make sure it’s the case and you are good to go.

0
source

Source: https://habr.com/ru/post/978919/


All Articles