wilson208
wilson208

Reputation: 352

Java Serialized Class Saved To File - How can i ensure backwards compatibility?

I have written an Android App for producing and saving 'Photography Services' Contracts to the device as a file for later printing. The class is pretty much made up of integers, doubles and Strings (including base64_encoded signatures).

The class implements serialisable. However, I am worried about I update the app, forget not to edit the class & edit it, reload onto my device and have X number of contracts saved to a file and then not be able to retrieve them.

Earlier I was browsing and found serialVersionUID. In a post I read that simply by implementing this simple long value, if i update the class it will still be able to be read. Is this correct? I read the java documentation for Serializable and couldnt make much of a decision on what the result of implementing serialVersionUID is.

Can anyone help shed some light on this for me? Just a simple yes this will work or no this wont work is sufficient and any links to help me learn will be even better!

Upvotes: 2

Views: 1171

Answers (1)

Lake
Lake

Reputation: 4092

To obtain backward compatibility with serialization, you have to

  1. Have the same serialVersionUID for the class you want to serialize throughout your versions.
  2. You can add/remove class methods as you like and it won't affect serialization.
  3. You can add as many new members as you like, and they will have the default value of their type right after the user updates the application to a new version.

Example:

// Old format
class FileFormat implements Serializable {
   static final long serialVersionUID = 44L;

   public String member1;
}

...
// New format
class FileFormat implements Serializable {
   static final long serialVersionUID = 44L;

   public String member1;
   public int member2;
}

In the above, the first time the user will read a file serialized with old FileFormat with the new application, s/he will obtain a new format FileFormat object with member2 set to 0. (Strings/Objects will be null, floats will be 0.0f, doubles 0.0, etc.).

  1. You cannot delete any field from the class (you will lose backward-compatibility)
  2. You cannot change the class' hierarchy in the means of moving the class up or down

There are many other restrictions, check out the official document: http://docs.oracle.com/javase/6/docs/platform/serialization/spec/version.html

Upvotes: 1

Related Questions