如何在 Java 中序列化不可序列化的对象? [英] How to serialize a non-serializable in Java?

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

问题描述

如何序列化未实现 Serializable 的对象?我无法将其标记为可序列化,因为该类来自 3rd 方库.

How can I serialize an object that does not implement Serializable? I cannot mark it Serializable because the class is from a 3rd party library.

推荐答案

你不能序列化一个没有实现 Serializable 的类,但你可以将它包装在一个实现的类中.为此,您应该在包装类上实现 readObjectwriteObject,以便您可以以自定义方式序列化其对象.

You can't serialise a class that doesn't implement Serializable, but you can wrap it in a class that does. To do this, you should implement readObject and writeObject on your wrapper class so you can serialise its objects in a custom way.

  • 首先,使您的不可序列化字段transient.
  • writeObject中,首先在流上调用defaultWriteObject来存储所有非瞬态字段,然后调用其他方法来序列化不可序列化对象的各个属性.
  • readObject中,首先调用流上的defaultReadObject来读回所有的非瞬态字段,然后调用其他方法(对应你添加到writeObject) 反序列化您的不可序列化对象.
  • First, make your non-serialisable field transient.
  • In writeObject, first call defaultWriteObject on the stream to store all the non-transient fields, then call other methods to serialise the individual properties of your non-serialisable object.
  • In readObject, first call defaultReadObject on the stream to read back all the non-transient fields, then call other methods (corresponding to the ones you added to writeObject) to deserialise your non-serialisable object.

我希望这是有道理的.:-)

I hope this makes sense. :-)

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

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