vendredi 15 avril 2016

Java Reflection and Singleton

Why reflection cannot break singleton pattern through breaking the private constructor through below code. There should be a new Instance on InstanctTwo but there is not.

Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
  //Below code will destroy the singleton pattern
  constructor.setAccessible(true);
  instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
  break;
}





Aucun commentaire:

Enregistrer un commentaire