java - 需要解释,为什么向 Singleton 类添加 implements Serializable 是不够的?

标签 java

谁能给我解释一下这是什么意思?特别是粗线。

To make a singleton class serializable, it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you have to declare all instance fields transient and provide a readResolve() method. Otherwise, each time a serialized instance is deserialized, a new instance will be created, leading, in the case of our example, to spurious Elvis sightings. To prevent this, add this readResolve() method to the Elvis class:

// Singleton with static factory
public class Elvis {
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() { ... }
    public static Elvis getInstance() { return INSTANCE; }
    public void leaveTheBuilding() { ... }
}

// readResolve method to preserve singleton property
private Object readResolve() {
    // Return the one true Elvis and let the garbage collector
    // take care of the Elvis impersonator.
    return INSTANCE;
}

仅供引用:这些行来自 Effective Java Book,第 3 项

最佳答案

readResolve 方法在 ObjectInputStream 从流中读取一个对象并准备将其返回给调用者时被调用。 ObjectInputStream 检查对象的类是否定义了 readResolve 方法。如果定义了该方法,则调用readResolve方法让流中的对象指定要返回的对象。

在单例情况下,我们将返回在类加载时创建的相同实例,并且不会返回任何新实例。所以保持单例。

关于java - 需要解释,为什么向 Singleton 类添加 implements Serializable 是不够的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440511/

相关文章:

java - Jquery 访客通知框

java - 上传并读取文件

java - MockMVC 返回空主体

java - 将自定义的 ObjectWriter 与 Jersey 一起使用

java - Android - 将 map v2 实现到抽屉导航

java - 从 String 创建唯一 id (int)

java - JVM 是否将内存分配给值为 null 的本地引用变量

java - 如何减慢java中特定方法的执行速度

Java 反射与代码生成

java - 根据任务结果取消计划的固定费率任务