Protect from reflection
Declare the instance
private constructor set be set public by reflection
Constructor constructor = ReflectionSingleton.class.getDeclaredConstructor();
// Below code will change constructor access level from private to public
constructor.setAccessible(true);
// Creating second instance
ReflectionSingleton instanceTwo = (ReflectionSingleton) constructor.newInstance();
private fields can be accessed by reflection
If you try to protect constructor, by throwing exception like below
private ReflectionSingleton() {
if (instance != null) {
throw new IllegalStateException("instance already created.");
}
System.out.println("Singleton instance is being created.");
}
Private static field's value can also be changed by reflection , like below
Sources :
Declare the instance
private constructor set be set public by reflection
Constructor constructor = ReflectionSingleton.class.getDeclaredConstructor();
// Below code will change constructor access level from private to public
constructor.setAccessible(true);
// Creating second instance
ReflectionSingleton instanceTwo = (ReflectionSingleton) constructor.newInstance();
private fields can be accessed by reflection
If you try to protect constructor, by throwing exception like below
private ReflectionSingleton() {
if (instance != null) {
throw new IllegalStateException("instance already created.");
}
System.out.println("Singleton instance is being created.");
}
Private static field's value can also be changed by reflection , like below
Field instance = ReflectionSingleton.class.getDeclaredField("instance");
| |||
/DesignPatterns
https://www.geeksforgeeks.org/prevent-singleton-pattern-reflection-serialization-cloning/
No comments:
Post a Comment