I was trying to break BillPaugh Singleton solution using reflection, well I am able to do it but I can see two constructors while accessing the BillPaughSingleTon solution. Why so ? Also by trial and error found that the line inside HelperClass is causing this. Again why so ?
BillPaughClass
package creational.BillPaugh;
public class SingleTonBillPaugh
{
private SingleTonBillPaugh instance;
public static SingleTonBillPaugh getInstance()
{
return SingleTonHelper.instance;
}
private SingleTonBillPaugh()
{
System.out.println(Thread.currentThread().getName() + " instance is going to be created");
}
static class SingleTonHelper
{
private static final SingleTonBillPaugh instance = new SingleTonBillPaugh(); //if we remove this line, multiple constructor will not be there. But this line is needed for singleton.
}
}
Breaking SingleTon using Reflection .
package creational.BillPaugh;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class BreakBillPaughUsingReflection
{
public static void main(String[] args)
{
SingleTonBillPaugh singletonInstance1 = SingleTonBillPaugh.getInstance();
System.out.println("singletonInstance1 " + singletonInstance1);
SingleTonBillPaugh singletonInstance2;
Constructor[] constructors = SingleTonBillPaugh.class.getDeclaredConstructors();
for (Constructor construct : constructors)
{
construct.setAccessible(true);
try
{
singletonInstance2 = (SingleTonBillPaugh) construct.newInstance();
System.out.println("singletonInstance2 " + singletonInstance2);
}
catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e)
{
e.printStackTrace();
}
}// end for
Constructor[] constructors2 = NormalClass.class.getDeclaredConstructors();
}
}
Proof of two constructor.
Aucun commentaire:
Enregistrer un commentaire