如何序列化一个 lambda? [英] How to serialize a lambda?

查看:25
本文介绍了如何序列化一个 lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何优雅地序列化 lambda?

How can I elegantly serialize a lambda?

例如,下面的代码抛出一个 NotSerializableException.如何在不创建 SerializableRunnable虚拟"接口的情况下修复它?

For example, the code below throws a NotSerializableException. How can I fix it without creating a SerializableRunnable "dummy" interface?

public static void main(String[] args) throws Exception {
    File file = Files.createTempFile("lambda", "ser").toFile();
    try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
        Runnable r = () -> System.out.println("Can I be serialized?");
        oo.writeObject(r);
    }

    try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
        Runnable  r = (Runnable) oi.readObject();
        r.run();
    }
}

推荐答案

Java 8 引入了 通过添加多个边界将对象转换为类型的交集.在序列化的情况下,因此可以这样写:

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

并且 lambda 会自动变得可序列化.

And the lambda automagically becomes serializable.

这篇关于如何序列化一个 lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆