mercredi 16 novembre 2016

How to stop creation of singleton class object using reflection even if I throw exception from private constructor ( without using enums)

As we know that an object can be created using reflection for singleton classes, however to stop it, we usually throw exception from private constructor. Refer to the code below

public class SingletonClass {

    private static SingletonClass instance = new SingletonClass();

    private SingletonClass(){
    // this will stop reflection attack..
    if(instance!=null){
        thrown Exception();
    }
    }   

    public static SingletonClass getInstance(){
        return instance;
    }

}

Please correct my understanding, but before invoking constructor to create object using reflection, I can even set instance field as null using reflection itself.. then in that case I can easily create object using reflection and bypass the check inside the constructor...

Is there a way to create new object in this case using reflection.. I don't want to use enums...

Aucun commentaire:

Enregistrer un commentaire