问题
Effective Java 2nd describes the Enum Implementation as the best practice to implement a Singleton in Java.
But the advantage of that implementation against the Static Holder Implementation is that the enum
can prevent the reflection attack.
So, there comes the question: Why do we need to prevent the reflection attack of singleton?
The other implementations of Java Singleton are just resolving the issues of multiple threads and lazy initialization.
These problems will and often appear at the daily development, but the reflection attack seems more like a Security Issue.
If the attacker can hack and crack your program, he and she could do whatever he and she wants, it seems it is no need to break the Singleton.
回答1:
@Wafer Li, in theory reflection could create a second instance of a non-enum
singleton, and so could deserialization. These are not "attacks" but ways that client code could defeat singletonness. The whole point of API writing is to guarantee documented behavior. If one leaves such a huge hole in the guarantee, why bother writing a singleton at all?
Also, lazy initialization of singletons is useless. Pointless. Static holder is redundant and just a whole bunch of code.
So why resist simple, elegant, fully-implemented, standard, best-practice enum
for singletons?
Why?
来源:https://stackoverflow.com/questions/44171031/why-java-singleton-needs-to-prevent-the-reflection-attack