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
Release: 2024-12-13 17:25:19
Original
988 people have browsed it

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?");
Copy after login

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!");
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template