0

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;
    }
}
Christian
  • 3,503
  • 1
  • 26
  • 47

2 Answers2

2

Otherwise one can create more than one object of your singleton class using cloning.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

... throwing a CloneNotSupportedException. Why?

You can check out the docs here:

protected Object clone() throws CloneNotSupportedException

Throws: CloneNotSupportedException - if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • I didn't ask why clone throws a CloneNotSupportedException. I asked, why would anyone implement that method if there is no interface Cloneable implemented anyway? – Christian Nov 15 '12 at 16:42
  • I don't understand why somebody trying to implement singleton would also implement the clone method. It doesn't make sense to me. – Bhesh Gurung Nov 15 '12 at 16:51
  • It doesn't. But I saw a lot of mentions in forums where developers are preventing cloning by implementing clone and throwing an exception. I ask why, because I can't imagine a hack. – Christian Nov 15 '12 at 17:02