How to prevent singleton from reflection in Java?
Singleton is a creational design pattern that restricts the instantiation of a class to one object, ensuring that there is only one instance of the class in the application. However, it is possible to create multiple instances of a singleton class using Reflection in Java.
To prevent singleton from Reflection, we can use an approach called "enum singleton". Here's how it works:
- Create an enum class that contains a single instance of the singleton object.
javaCopy codepublic enum Singleton {
INSTANCE;
// define methods and variables for the singleton object here
}
- Use the
Singleton.INSTANCE
reference to access the singleton object.
javaCopy codeSingleton singleton = Singleton.INSTANCE;
By using an enum to implement the singleton pattern, we can prevent multiple instances of the singleton class from being created even if Reflection is used to create new instances. This is because enums in Java are guaranteed to have only one instance created during the lifetime of an application.
In addition to being Reflection-proof, enum singletons are also thread-safe and are guaranteed to be serialization-safe out of the box.