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();
}
question from:
https://stackoverflow.com/questions/6994393/singleton-how-to-stop-create-instance-via-reflection 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…