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

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

问题描述

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

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天全站免登陆