Ofer
Ofer

Reputation: 289

Removing fields from a class and updating existing serialized files

I already have a serialized file containing instances of class X. I Now decided to modify the code of class X by removing a field that is no longer needed. What’s the best way to update my existing serialized file accordingly?

The only solution I have in mind so far is:

  1. Creating a temporary class Y which is identical to X but without the unwanted field.
  2. Deserializing the X instances from the file, constructing their equivalent Y instances, and serializing them to a new file.
  3. Removing the unwanted field from the code of class X and then doing step 2 in reverse.

That’s a horrible mess (especially since this situation is common for me). Any better way?

Thanks!

Upvotes: 0

Views: 995

Answers (1)

user207421
user207421

Reputation: 311018

You don't need to do anything to the file. The deleted field data will be ignored by deserialization to the modified class. Just make sure you don't disturb the value of the serialVersionUID, and if you haven't provided one, do so now, using the output of the serialver tool, before you make the change.

You need to have a good look at the Versioning chapter of the Object Serialization Specification.

Upvotes: 2

Related Questions