Java 序列化:readObject() 与 readResolve() [英] Java serialization: readObject() vs. 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.
未回答的问题是:
- 这两种方法有什么区别?
- 什么时候应该实施哪种方法?
- 应该如何使用
readResolve()
,尤其是在返回什么方面?
- What is the difference between the two methods?
- When should which method be implemented?
- How should
readResolve()
be used, especially in terms of returning what?
我希望你能对这件事有所了解.
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屋!