I know in Java we can create an instance of a Class by new
, clone()
, Reflection
and by serializing and de-serializing
.
I have create a simple class implementing a Singleton.
And I need stop all the way one can create instance of my Class.
public class Singleton implements Serializable{ private static final long serialVersionUID = 3119105548371608200L; private static final Singleton singleton = new Singleton(); private Singleton() { } public static Singleton getInstance(){ return singleton; } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Cloning of this class is not allowed"); } protected Object readResolve() { return singleton; } //-----> This is my implementation to stop it but Its not working. :( public Object newInstance() throws InstantiationException { throw new InstantiationError( "Creating of this object is not allowed." ); } }
In this Class I have managed to stop the class instance by new
, clone()
and serialization
, But am unable to stop it by Reflection.
My Code for creating the object is
try { Class<Singleton> singletonClass = (Class<Singleton>) Class.forName("test.singleton.Singleton"); Singleton singletonReflection = singletonClass.newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }
Prevent Singleton Pattern From Deserialization To overcome this issue, we need to override readResolve() method in the Singleton class and return the same Singleton instance.
Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance.
Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.
1. Reflection: In Java, Reflection API is used to explore or change the behavior of methods, interfaces, classes at runtime. As you can see that 2 different hashcodes are created for singleton class. Hence singleton pattern has been destroyed using Reflection.
By adding below check inside your private constructor
private Singleton() { if( singleton != null ) { throw new InstantiationError( "Creating of this object is not allowed." ); } }
Define the singleton like this:
public enum Singleton { INSTANCE }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With