Consider I have a Singleton class defined as follows.
public class MySingleton implements Serializable{
private static MySingleton myInstance;
private MyS
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);
}
}