这个Singleton是否对序列化和反射攻击都有抵抗? [英] is this Singleton resistant to both Serialization and Reflection Attacks?
问题描述
以下代码是否对序列化和反射攻击都有效?
public class Example {
private static Example instance = new Example();
private Example(){}
public static示例getInstance(){
return instance;
}
}
要引用Joshua Bloch,
自版本1.5开始,有三种
方法来实现单例。
只需创建一个带有
元素的枚举类型:
/ enum singleton - 首选方法
public enum Elvis {
INSTANCE;
public void leaveTheBuilding(){...}
}
< blockquote>
这种方法在功能上是
相当于公共字段
方法,除了它更多
简洁,提供序列化
机器免费,和提供一个
的保证,即使面对
复杂的序列化或
反射攻击,多个
实例化。
参考。
编辑:
如果你想知道为什么,根据Joshua Bloch,
为了保持单例保证,
您必须声明所有实例字段
transient
并提供
readResolve
方法。否则,每个
时间一个序列化的实例是
反序列化,一个新的实例将
创建...
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;
}
}
To quote Joshua Bloch,
As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis{
INSTANCE;
public void leaveTheBuilding(){...}
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.
EDIT:
If you want to know why, according to Joshua Bloch,
To maintain the singleton guarantee, you have to declare all instance fields
transient
and provide areadResolve
method. Otherwise, each time a serialized instance is deserialized, a new instance will be created ...
这篇关于这个Singleton是否对序列化和反射攻击都有抵抗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!