I am messing around with Java serialization of lambdas.
I have two completely separate projects that have a single class in them.
Project 1:
class TestMain {
public static void main(String[] args) {
Runnable r = (Runnable & Serializable) () -> {};
// Serialize r to C:/file.ser;
}
}
Project 2:
class TestMain2 {
public static void main(String[] args) {
// Deserialize C:/file.ser to runnable;
}
}
However, upon attempting to deserialize the runnable, it throws an exception saying it can't find TestMain
...is there any way I can avoid this?
The solution is to include TestMain on the classpath when you are deserializing.
The lambda implicitly depends on the outer class in which it is declared.
Also, the Java Tutorial says this:
However, like inner classes, the serialization of lambda expressions is strongly discouraged.
Besides ... as @Tim points out ... even if you didn't need the TestMain.class file, you would still need the TestMain$xxx.class file that contained the lambda's code.
...is there any way I can avoid this?
Broadly speaking, no.
Serialization is a method for persisting data, not code. The code for the serialized class needs to exist at deserialization time, inside the JVM in which you are doing the deserializing.
It sounds like you're trying to pass code between two JVMs.
There are techniques for doing that, but not via serialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With