lambda创建后的序列化 [英] Serialization of a lambda after its creation

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

问题描述

我可以使用以下语法序列化lambda

Runnable r = (Runnable & Serializable) () -> System.out.println("");
try (ObjectOutput oo = new ObjectOutputStream(new ByteArrayOutputStream())) {
  oo.writeObject(r);
}

但是,如果我从客户端代码收到lambda并且它还没有被转换恰当地说,我无法将其序列化。

However if I receive the lambda from a client code and it has not been cast appropriately, I can't serialize it.

如何在不更改其定义的情况下序列化 r

How can I serialize r below without changing its definition:

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






我试图序列化派生对象:


I have tried to serialize a "derived" object:

Runnable r1 = (Runnable & Serializable) r::run;
Runnable r2 = (Runnable & Serializable) () -> r.run();

但在每种情况下, oo.writeObject(rxxx); 失败并带有 NotSerializableException

but in each case, oo.writeObject(rxxx); fails with a NotSerializableException.

推荐答案

这是正确的,并按设计。正如您无法在实例化后获取非可序列化对象并使其可序列化一样,一旦创建了lambda,就会设置其可序列化。

This is correct, and by design. Just as you cannot take a non-serializable object and make it serializable after instantiation, once a lambda is created, its serializability is set.

如果lambda的目标类型是可序列化的(并且其捕获的参数是可序列化的),则lambda是可序列化的。您的第一个示例是可序列化的,因为目标类型是交集(Runnable&序列化)。您的两次尝试转换 r 失败,因为在这两种情况下, r 是一个不可序列化的捕获变量,因此生成的lambda表达式/方法引用不可序列化。 (绑定方法引用的接收器充当捕获变量。)

A lambda is serializable if its target type is serializable (and its captured arguments are serializable.) Your first example is serializable because the target type is the intersection (Runnable & Serializable). Your two attempts to convert r fail because in both cases, r is a captured variable that is not serializable, and so the resulting lambda expression / method reference is not serializable. (The receiver for a bound method reference acts as a captured variable.)

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

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