Breach of Singleton pattern by instantiating with reflection API
Closed this issue · 1 comments
mainul35 commented
With Reflection API, singleton pattern can be breached. The code snippet is as follows.
Car objectOne = Car.getInstance();
Car objectTwo = Car.getInstance();
System.out.println(objectOne);
System.out.println(objectTwo);
// Breaching with reflection API
Class clazz = Class.forName("com.msi.creationaldesignpattern.singleton.Car");
Constructor<Car> ctor = clazz.getDeclaredConstructor();
ctor.setAccessible(true);
Car objectThree = ctor.newInstance();
System.out.println(objectThree);
Output
com.msi.creationaldesignpattern.singleton.Car@15db9742
com.msi.creationaldesignpattern.singleton.Car@15db9742
com.msi.creationaldesignpattern.singleton.Car@6d06d69c