Category Archives: Reflection

Breaking singleton pattern


Singleton pattern in java can be implemented by the approaches explained here

Now here is the code to break it using reflection


public class NormalClass{

 private NormalClass(){ //having private constructor
 }

 private void print(){
 System.out.println("broken");
 }

}

/////////////////////////////////

public class Main{

 public static void main(String[] args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

 Class c = NormalClass.class;
 final Constructor con = c.getDeclaredConstructor();
 System.out.println(con);

 final Method meth = c.getDeclaredMethod("print", null);

//---- You will get IllegalAccessException without this ---
AccessController.doPrivileged(new PrivilegedAction() {

public Object run() {
 con.setAccessible(true);// turning off the access check
 meth.setAccessible(true);// turning off the access check
return null;
 }

});

 NormalClass n = (NormalClass)con.newInstance(null);
 meth.invoke(n,null);
 }

}

Advertisements