How to deal with Singleton along with Serialization

后端 未结 9 1611
感情败类
感情败类 2020-12-04 13:06

Consider I have a Singleton class defined as follows.

public class MySingleton implements Serializable{
 private static MySingleton myInstance;

 private MyS         


        
9条回答
  •  星月不相逢
    2020-12-04 13:51

    Here is the Answer for Breaking the Singleton class and and how to prevent our class from creating different object by using readResolve() methood;

    import java.io.Serializable;

    public class Singleton implements Serializable {

    private static final long serialVersionUID = 1L;
    
    private Singleton() {
    }
    
    private static class SingletonHelper {
    
        private static final Singleton INSTANCE = new Singleton();
    
    }
    
    public static Singleton getInstance() {
    
        return SingletonHelper.INSTANCE;
    }
    
    private Object readResolve() {
        Singleton instance = getInstance();
        return instance;
    }
    

    }

    public class BreakSIngletonUsingSerialization {

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    
        Singleton demo1 =Singleton.getInstance();
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("C:/Eclipse/serial.ser"));
        out.writeObject(demo1);
        Singleton demo2 =null;
        ObjectInput in = new ObjectInputStream(new FileInputStream("C:/Eclipse/serial.ser"));
    
        demo2 = (Singleton)in.readObject();
    
        System.out.println("Hascode demo1 : " +demo1);
        System.out.println("Hascode demo2 : " +demo2);
    }
    

    }

提交回复
热议问题