Java序列化:readObject()与readResolve() [英] Java serialization: readObject() vs. readResolve()

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

问题描述

本书 Effective Java 和其他资源提供了一个很好的解释,说明在使用可序列化的Java类时如何以及何时使用readObject()方法。另一方面,readResolve()方法仍然有点神秘。基本上我发现的所有文件要么只提及两者中的一个,要么仅单独提及。

The book Effective Java and other sources provide a pretty good explanation on how and when to use the readObject() method when working with serializable Java classes. The readResolve() method, on the other hand, remains a bit of a mystery. Basically all documents I found either mention only one of the two or mention both only individually.

尚未得到答复的问题是:

Questions that remain unanswered are:


  • 这两种方法有什么区别?

  • 何时应该实施哪种方法?

  • 如何应该使用readResolve(),特别是在返回什么方面?

我希望你能解释一下这个问题。

I hope you can shed some light on this matter.

推荐答案

readResolve 用于替换对象从流中读取。我见过的唯一用途是强制执行单身人士;读取对象时,将其替换为单例实例。这可以确保没有人可以通过序列化和反序列化单例来创建另一个实例。

readResolve is used for replacing the object read from the stream. The only use I've ever seen for this is enforcing singletons; when an object is read, replace it with the singleton instance. This ensures that nobody can create another instance by serializing and deserializing the singleton.

这篇关于Java序列化:readObject()与readResolve()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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