Is the following code resistant to both Serialization and Reflection Attacks?
public class Example{
private static Example instance=new Example();
private E
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.
Reference.
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 ...