I saw a lot of people implementing the clone
method for singletons, which are throwing a CloneNotSupportedException
. Why?
How for example could this be hacked by cloning or any other way? Btw. I have read effective java and know about enums.
public final class Elvis implements Serializable {
public final static transient Elvis INSTANCE = new Elvis();
private Elvis() {
if(INSTANCE != null) {
throw new IllegalStateException("This is a singleton. Don't try to instantiate it.");
}
}
private Object readResolve() {
//serialization protection
return INSTANCE;
}
}