Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization of lambda [duplicate]

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?

like image 745
Cheetah Avatar asked Sep 22 '26 13:09

Cheetah


2 Answers

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.

like image 104
Stephen C Avatar answered Sep 25 '26 03:09

Stephen C


...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.

like image 20
Tim Avatar answered Sep 25 '26 04:09

Tim