Bootstrap

如何防止序列化破坏单例模式

    反射和序列化都可以破解懒汉式和饿汉式。下面来讨论一下如何防止序列化来破坏单例模式,

反序列化时会调用readObject方法,里面会判断是否有重写readResolve方法,如果重写了就会执行readResolve方法,并将方法的返回值返回,我们可以利用这一点,在单例模式的类中实现readResolve方法,将单例对象返回回来,这样序列化就不能破坏单例了。

代码如下:

package com.example.demo.entity;

import java.io.*;

public class Singleton implements Serializable{
    private static Singleton singleTon = new Singleton();

    private Singleton(){
    }

    public static Singleton getInstance(){
        return singleTon;
    }

    private Object readResolve(){
        return Singleton.singleTon;
    }


    public static void main(String[] args) throws Exception {
        Singleton instance = Singleton.getInstance();

        //把对象写入文件
        File file = new File(
                "a.txt");
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(instance);
        oos.close();
        fos.close();

        //序列化把对象读取
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Singleton serilizeInstance = (Singleton) ois.readObject();

        System.out.println(instance == serilizeInstance);
    }
}

;