transient for serializing singleton

后端 未结 3 605
醉酒成梦
醉酒成梦 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:36

    try {
                c=MySingleton.getInstance();
                c.setState(25);
                FileOutputStream fs = new FileOutputStream("testSer.ser");
                ObjectOutputStream os = new ObjectOutputStream(fs);
                os.writeObject(c);
                os.close();
     }
    

    You are getting 25 because you are setting that value in the object. Refer above code. I think you were expecting the answer to be 15?

提交回复
热议问题