这个单例能够抵抗序列化和反射攻击吗?
以下代码是否能够抵抗序列化和反射攻击?
public class Example{
private static Example instance=new Example();
private Example(){}
public static Example getInstance(){
return instance;
}
}
Is the following code resistant to both Serialization and Reflection Attacks?
public class Example{
private static Example instance=new Example();
private Example(){}
public static Example getInstance(){
return instance;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
引用约书亚·布洛赫的话:
参考。
编辑:
如果你想知道为什么,根据 Joshua Bloch 的说法,
To quote Joshua Bloch,
Reference.
EDIT:
If you want to know why, according to Joshua Bloch,
不,事实并非如此。有更好的技术。
尝试这样的事情:
No, it is not. There is a better technique.
Try something like this:
恕我直言,面向对象设计并不是为了防止攻击。不过,无论合同、不称职或编程错误如何,它都有助于防止由于理解不良而导致类的不当使用和错误。
由于您的示例类不可序列化,因此我想说在这种情况下序列化不是问题。关于反射,如果有人用它来创建你的单例的另一个实例,那么在我看来他显然是恶意的,并且无论如何都有搬起石头砸自己脚的风险。
OO design is not meant to prevent attacks, IMHO. It can be useful to prevent inappropriate usage of your classes and bugs due to bad comprehension, irrespect of the contract, incompetence, or programming errors, though.
Since your Example class is not serializable, I would say that serialization is not a problem in this case. Regarding reflection, if someone uses it to create another instance of your singleton, then he's obviously malicious IMO, and risks shooting himself in the foot anyway.
就反射而言,上下文中的单例并不是反射证明。您可以使用 setAccesssible(true) 来获取私有构造函数并实例化单例。您可以在以下位置获得有关此事的更多详细信息 -
http://technonstop.com/java-singleton-reflection-and-lazy-initialization
As far as reflection is concerned , the singleton in context is NOT reflection proof. U can use setAccssible(true) to get hold of private constructor and instantiate the singleton. You can get more details about this thing at -
http://technonstop.com/java-singleton-reflection-and-lazy-initialization