Remove field from old Java class implementing Serializable

Suppose I have a version of the MyClass class, where I have two fields int count and String name . And I saved a stream of bytes for the file. After I remove the name attribute from the class, then the persistent byte stream is also converted to an object without problems.

But according to Serializable docs adding new attribute is compatible change but deleting attribute is incompatible change wrt Serilaization . I'm confused, can someone please help me figure this out. Thanks!!!!

+4
source share
2 answers

A few points:

When an object is deserialized, any fields not found in the byte stream will be initialized to null . Therefore, when adding a new field, when the object of the new version is deserialized from the byte of the old version, the new field will be initialized to null . If null is considered an invalid value, you can provide the readObject method to handle the conversion. Older versions can still be deserialized from the new byte stream - the new field is simply ignored.

If the field is deleted, the situation will change to the opposite: the field will not be present in the class of the old version. Invalid field will be set to null . However, unlike the previous case, the old version cannot add the readObject method (if you can add this method, this will be the last new version). Therefore, deleting a field is considered incompatible .

Thus, the ability to create the readObject method in the new version class allows it to handle the byte stream of the old version when adding a new field. Unfortunately, the opposite is not possible.

It is important to note that unless specifically defined, the serialVersionUID field will be automatically generated and most likely will change with almost all noticeable changes in the class. If two versions of the classes have different serialVersionUID , an exception will be thrown when trying to serialize / deserialize in the byte stream of an older or newer version. If you do not manually install serialVersionUID , then no version of your class will be serializable.

PS If null is a valid state for a remote field (in the old version), then I think you can delete the fields. However, this is probably a regional case.

+9
source

If the serialVersionUID parameter remains the same, adding and deleting fields are compatible according to the rules defined in the chapter "Object Versions" in the "Serializing Objects" section, which you must read.

+2
source

All Articles