Java 写入 readResolve方法解决 单例类序列化后破坏唯一实例规则的问题

Java 写入 readResolve方法解决 单例类序列化后破坏唯一实例规则的问题

  • 单例类序列化后, 在反序列化会克隆出新的对象破坏了单例规则. 所以需要序列化的单例类需要含有 readResolve方法. 反序列化时会自动调用此方法返回对象, 来保证对象唯一性

public class EagerSingleton implements Serializable {
    private static final long serialVersionUID = 7073777279565036708L;

    private static volatile EagerSingleton instance = new EagerSingleton();

    /**
     * 为了防止通过反射机制实例化构造方法抛异常
     * */
    private EagerSingleton() {
        if (instance != null) {
            throw new RuntimeException("不允许被反射实例化");
        }
    }

    public static EagerSingleton getInstance() {
        return instance;
    }

    /**
     * readResolve方法的作用为防止序列化单例时破坏唯一实例的规则
     * */
    private Object readResolve() throws ObjectStreamException {
        return instance;
    }

}

public class App {
    public static void main(String[] args) {
        EagerSingleton o = EagerSingleton.getInstance();
        System.out.println("通过单例类实例化对象 " + EagerSingleton.getInstance());

        try {
            File file = new File("D:" + File.separator + "EagerSingleton");
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            /** 对象写入到文件*/
            oos.writeObject(o);

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            /** 从磁盘读取对象*/
            System.out.println("从磁盘读取的对象 " + ois.readObject());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

  • 输出 (单例类不包含 readResolve方法时

通过单例类实例化对象 com.test.web4.singleton.EagerSingleton@eed1f14
从磁盘读取的对象 com.test.web4.singleton.EagerSingleton@7a07c5b4

  • 输出 (单例类包含 readResolve方法时

通过单例类实例化对象 com.test.web4.singleton.EagerSingleton@eed1f14
从磁盘读取的对象 com.test.web4.singleton.EagerSingleton@eed1f14

  • 可以看出对象地址包含 readResolve方法和不包含是有区别的

如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!

发布了62 篇原创文章 · 获赞 325 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qcl108/article/details/102258871