java static variable serialization

前端 未结 1 990
Happy的楠姐
Happy的楠姐 2021-01-15 04:17

How are the values of static variables persisted during serialization(If at all persisted). I have read similar questions on stack where it says that static variables are in

1条回答
  •  清酒与你
    2021-01-15 05:05

    The static field value was not serialized. The output is printing the new value of the static field simply because you modified it to 999999 but you never reset its value to the old one before de-serizalizing. Since the field is static, the new value is reflected in any instance of ChildClass.

    To properly assert that the field is not serialized, reset the value to 10001 before de-serializing the object, and you will notice that its value is not 999999.

    ...
    ChildClass.setStaticState(10001);
    
    FileInputStream fi = null;
    ObjectInputStream ois = null;
    ChildClass streamed;
    
    ...
    // when de-serializing, the below will print "state101 static state 10001"
    System.out.println(streamed.toString());
    

    0 讨论(0)
提交回复
热议问题