rakesh kapri rakesh kapri - 22 days ago 9
Java Question

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 new 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 stop object creation using reflection in this case.. I don't want to use enums...

Answer

Although I don't understand why you would be so extremely protecting your objects, people will always be able to call setAccessible() unless you are using java 9, where you can choose to not export your class in your module.