Consider I have a Singleton class defined as follows.
public class MySingleton implements Serializable{
private static MySingleton myInstance;
private MyS
The best way to do this is to use the enum singleton pattern:
public enum MySingleton {
INSTANCE;
}
This guarantees the singleton-ness of the object and provides serializability for you in such a way that you always get the same instance.
More generally, you can provide a readResolve()
method like so:
protected Object readResolve() {
return myInstance;
}