Java serialization, UID not changed. Can I add new variables and method to the class?

前端 未结 4 1009
深忆病人
深忆病人 2020-12-02 19:27

I have a class that is serialised. Now I need to add a new variable into the class, with setter and getter methods. This class is sent over wire in RMI.

Without chan

4条回答
  •  我在风中等你
    2020-12-02 19:56

    If you hard-code the SerialVersionUID of a class, (to 1L, usually), store some instances, and then re-define the class, you basically get this behavior (which is more or less common sense):

    1. New fields (present in class definition, not present in the serialized instance) are assigned a default value, which is null for objects, or the same value as an uninitialized field for primitives.
    2. Removed fields (not present in class definition but present in the serialized instance) are simply ignored.

    So the general rule of thumb is, if you simply add fields and methods, and don't change any of the existing stuff, AND if you're OK with default values for these new fields, you're generally OK.

提交回复
热议问题