Remove fields from old Java classes that implement serializable

Suppose I have a version of the MyClass class, where I have two fields int count and string name I have saved the byte stream to a file After removing the attribute name from the class, the persistent byte stream is also converted to an object without any problem

However, according to the serializable document, adding new attributes is a compatible change, but deleting attributes is an incompatible change w.r.t. serialization I'm confused. Someone can help me understand this thank you!!!!

Solution

what time?

When an object is deserialized, any fields not found in the byte stream are initialized to null Therefore, when you add a new field and deserialize the new version object from the old version byte stream, the new field will be initialized to null If NULL is considered an invalid value, the readObject method can be provided to handle the conversion The old version can still deserialize from the new byte stream - the new field is simply ignored

If you delete a field, the opposite is true: the old version of the class will now lose a field Missing 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, it will become the latest version) Therefore, deleting fields is considered incompatible

In short, the ability to create the readObject method in the new version of the class allows it to handle the old version of the byte stream when adding new fields Unfortunately, the reverse is impossible

It is important to note that unless specifically defined, the serialVersionUID field will be generated automatically and is likely to change with all significant changes to the class If two class versions have different serialversionuids, an exception will be thrown when trying to serialize / deserialize an older or newer version of the byte stream If you do not set the serialVersionUID manually, any version of your class will not be serializable

Attachment: if NULL happens to be the valid state of the deleted field (in the old version), I guess you can delete the field However, this may be a marginal situation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>