Why Java Singleton needs to prevent the reflection attack

烈酒焚心 提交于 2021-02-10 06:09:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!