为什么 Java Singleton 需要防止反射攻击 [英] Why Java Singleton needs to prevent the reflection attack

查看:46
本文介绍了为什么 Java Singleton 需要防止反射攻击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Effective Java 2nd枚举实现描述为在 Java 中实现单例的最佳实践.

Effective Java 2nd describes the Enum Implementation as the best practice to implement a Singleton in Java.

但是该实现相对于 Static Holder 实现 的优势在于 enum 可以防止反射攻击.

But the advantage of that implementation against the Static Holder Implementation is that the enum can prevent the reflection attack.

那么,问题来了:为什么要防止singleton的反射攻击?

So, there comes the question: Why do we need to prevent the reflection attack of singleton?

Java 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.

推荐答案

@Wafer Li,理论上反射可以创建非enum 单例的第二个实例,反序列化也可以.这些不是攻击",而是客户端代码可以打败单例性的方式.API 编写的全部要点是保证记录的行为.如果在保证中留下如此大的漏洞,为什么还要写一个单例呢?

@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.

那么为什么要抵制单例的简单、优雅、完全实现、标准、最佳实践的enum?

So why resist simple, elegant, fully-implemented, standard, best-practice enum for singletons?

为什么?

这篇关于为什么 Java Singleton 需要防止反射攻击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆