Talha Ahmed Khan Talha Ahmed Khan - 3 months ago 7
Java Question

Singleton: How to stop create instance via Reflection

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();
}

Answer

Try creating your public constructor

private Singleton() {
    if( Singleton.singleton != null ) {
        throw new InstantiationError( "Creating of this object is not allowed." );
    }
}
Comments