Serializing Lambdas in Java
Attempting to serialize a lambda in Java can result in a NotSerializableException. This article explores how to elegantly overcome this hurdle without resorting to creating a SerializableRunnable "dummy" interface.
In the example provided, the lambda is defined as:
Runnable r = () -> System.out.println("Can I be serialized?");
Writing this lambda to an ObjectOutputStream throws the NotSerializableException.
Solution
Java 8 introduces the ability to cast an object to an intersection of types. This can be leveraged in the context of serialization, as shown below:
Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");
This cast effectively modifies the lambda to implement both the Runnable and Serializable interfaces. Consequently, the lambda becomes serializable without the need for a separate "dummy" interface.
The above is the detailed content of How Can I Serialize a Java Lambda Without Creating a Dummy Interface?. For more information, please follow other related articles on the PHP Chinese website!