如何在序列化的世界中保证Java实例控制(没有枚举)?
在Java 1.5之前的世界(所以没有enum
)并且我的对象被序列化,我该如何强制执行适当的实例控制? 我说的是这样一个类,据我所知,我不确定instance0和instance1将永远是唯一的实例。
import java.io.Serializable; public final class Thing implements Serializable { private static final long serialVersionUID = 1L; public static final Thing instance0 = new Thing(); public static final Thing instance1 = new Thing(); private Thing(){}; }
你应该看看Effective Java 。 关于Singleton的章节对此有所解决,并且有一章关于Typesafe Enum模式,这肯定会影响enum
实现的方式。
简短的回答是你必须实现readResolve
。
如果我理解正确,那么你要找的是采用Joshua Bloch的建议并实现readResolve方法来返回你的一个常量实例。
private Object readResolve() throws ObjectStreamException { return PRIVATE_VALUES[ordinal]; // The list holding all the constant instances }
此链接是sun的一个示例,与其他海报建议的Effective Java中提供的解决方案类似。