Sunday, October 27, 2013

I know in Java we can create an instance of a Class by newclone()Reflection and byserializing 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 newclone() 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();
}
share|improve this question
 
You have accepted the wrong answer - the right one is stackoverflow.com/a/6994437/281545 –  Mr_and_Mrs_DSep 28 at 18:15

6 Answers

up vote10down voteaccepted
Try creating your public constructor
private Singleton() {
    if( Singleton.singleton != null ) {
        throw new InstantiationError( "Creating of this object is not allowed." );
    }
}
share|improve this answer

No comments:

Post a Comment