I have a question about Java serialization in scenarios where you may need to modify your serializable class and maintain backward compatibility.
I come from deep C# experience, so please allow me to compare Java with .NET.
In my Java scenario, I need to serialize an object with Java's runtime serialization mechanism, and store the binary data in permanent storage to reuse the objects in future. The problem is that, in the future, classes may be subject to changes. Fields may be added or removed.
I don't know Java serialization in the deep, except for this fantastic article about how not to program in Java when dealing with serialization. As I imagine(d), the serialVersionUID plays a key role in Java serialization, and this is where I need your help.
Apart from the article's example (I know it's bad coding), shall that field not be modified when Eclipse asks to update it after I modified the class?
I remember from the .NET world that when I add new fields I must add the [OptionalField]
Attribute to the field to get the backward compatibility, so CLR won't require it in old serialized data. Also, when I need to deprecate a field I must only remove the public methods and not the private fields.
What are the guidelines for best serialization?
Thank you.
[Add] Here is an example. Suppose I have class Foo
public class Foo {
private String bar;
}
Then I change to:
public class Foo {
private String bar;
private Integer eggs;
}
Is compatibility broken between these two version? If I deserialize an "oldFoo" when I have the "newFoo" compiled, does eggs equals null or is an exception thrown? I prefer the first, obviously!!