How to prevent Singleton Class from Reflection and Serialization

First create a singleton class.



If we will try to clone it, it will throw Exception. 


Now try to break the Singleton with Reflection


How to prevent Object Creation with Reflection - Check in the private constructor if object already created then throw an exception.


If we run the reflection code, we will get this exception.



Prevent Singleton Class from Serialization



We have to override the read resolve method










Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Optional Vs Null Check