One of my colleagues at work raised a question regarding ‘breaking the singleton’ using Java Reflection, and asked of a way to avoid such actions. It inspired me, and started to think about a way to avoid it, and following is the outcome of it.
A word of caution before continuing any further. I do not recommend at all that any of the following methods (except for SecurityManagers) shall be used in your code to restrict reflective access to your singletons. Such access is possible in Java because there is a good reason. Sometimes, when you are working with old code (may be even not so old code), you might need to be able to reflectively access the singleton, and you might not be able to predict that at the time of writing your code.
Singleton pattern can be broken using reflection, as shown below.