Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialization version conflicts

My question is what is a good way to implement upgrading outdated objects?

For example say you have a class like this:

public class Foo() implements Serializable {
    int a;
    String b;
}

and then you serialize this object. Then later on you add more functionality to your class by say adding:

...
int c;
...

You still want to retain the information that is in the serialized object but I know that if you try to deserialize it there will be conflicts. So is there a way (maybe by checking serialVersionUID) to set a value for int c knowing that it won't exist?

Thanks

like image 958
Adam Keenan Avatar asked Nov 22 '12 08:11

Adam Keenan


2 Answers

Deprecate the existing class, create a new class with the new structure and implement a constructor in the new class that can take the old object and convert it to the new version.

Assuming you created your old class against an interface, you can implement the same interface with the new class and the new objects will still be compatible with your old class.

like image 87
codeghost Avatar answered Sep 22 '22 23:09

codeghost


You would need to add a private method:

    private void readObject(ObjectInputStream ois) {
      // compare serialVersionUID and determine which fields to expect
      // read the expected fields for that version
      // initialize the new fields.
    }

For more information, read the serialization specs

like image 31
Akber Choudhry Avatar answered Sep 19 '22 23:09

Akber Choudhry