is this Singleton resistant to both Serialization and Reflection Attacks?

后端 未结 5 391
死守一世寂寞
死守一世寂寞 2021-02-04 22:25

Is the following code resistant to both Serialization and Reflection Attacks?

public class Example{
  private static Example instance=new Example();

  private E         


        
5条回答
  •  感情败类
    2021-02-04 22:52

    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 a readResolve method. Otherwise, each time a serialized instance is deserialized, a new instance will be created ...

提交回复
热议问题