How to serialize a lambda? How to serialize a lambda? java java

How to serialize a lambda?


Java 8 introduces the possibility to cast an object to an intersection of types by adding multiple bounds. In the case of serialization, it is therefore possible to write:

Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");

And the lambda automagically becomes serializable.


The same construction can be used for method references. For example this code:

import java.io.Serializable;public class Test {    static Object bar(String s) {        return "make serializable";    }    void m () {        SAM s1 = (SAM & Serializable) Test::bar;        SAM s2 = (SAM & Serializable) t -> "make serializable";    }    interface SAM {        Object action(String s);    }}

defines a lambda expression and a method reference with a serializable target type.


Very ugly cast. I prefer to define a Serializable extension to the functional interface I'm using

For example:

interface SerializableFunction<T,R> extends Function<T,R>, Serializable {}interface SerializableConsumer<T> extends Consumer<T>, Serializable {}

then the method accepting the lambda can be defined as such :

private void someFunction(SerializableFunction<String, Object> function) {   ...}

and calling the function you can pass your lambda without any ugly cast:

someFunction(arg -> doXYZ(arg));