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); } }
if you throw Exception from constructor then you might not be able to break 🙂
Javin
Why String is immutable in Java
It is not clear if you are defining a workaround to get around a class you would like to interact with under different terms (other multiplicity) or providing a critique of the design pattern based on this limitation.
Either way, I would say it is important to recognize that the usage of a design pattern shows intent as does actively working to circumvent one. The singleton pattern shows other developers on a team or consumers of an API that the designer feels it is important to limit the number of instances to achieve some objective. Working around the constraint imposed by the design pretty much promises adverse effects. There are probably a few circumstances where this constitutes a security risk, which can be managed with the correct usage of the Java security manager. Usually, the code just won’t work right.
Anyone concerned about the potential of this should consider using what Bloch calls the “best way to implement a singleton” (Item 4 in Effective Java): create an enum type with one element. This “provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks”. (Bloch)
This is nothing new. In general, you can say that access modifiers can be broken by using reflection. So what? If anyone uses reflection to “break” a singleton pattern, he obviously does so on purpose. That means he knows he’s breaking a pattern. So he knows he can expect a lot of trouble.
use enum to overcome this problem