Home >Java >javaTutorial >How Can I Serialize a Java Lambda Without Creating a Dummy Interface?

How Can I Serialize a Java Lambda Without Creating a Dummy Interface?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 17:25:191071browse

How Can I Serialize a Java Lambda Without Creating a Dummy Interface?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn