transient for serializing singleton

后端 未结 3 610
醉酒成梦
醉酒成梦 2020-12-18 17:18

Effective Java - To maintain the singleton guarantee, you have to declare all instance fields transient and provide a \'readResolve\' method. What do we achieve by declaring

3条回答
  •  没有蜡笔的小新
    2020-12-18 17:54

    Irrespective of whether I declare the 'state' variable as transient or not ,I get c.getState() gettign printed out as 25. Am I Missing something here?

    You replace your deserialized object, because readResolve() returns the private static instance of MySingleton, thus overriding the instance returned by the deserialization.

提交回复
热议问题