Object serialization and deserialization when class field changed
I have a question about Object serialization and deserialization when class field changed.
If an object with type MyClass
MyClass {
String str1;
LinkedList mylist = new LinkedList();
String str2;
}
has been serialized to file.
Then I changed the code which changes MyClass definition to
MyClass {
String str1;
LinkedList mylist = new LinkedList();
Map myMap = new HashMap();
}
After that, I deserialize the object from file to a MyClass object using the changed code. Is it OK? Will there any exception thrown during deserialization? I want to reuse the old object. I.e. I want the de-serializing can be done. So I hope th开发者_如何转开发ere is no exception thrown.
Thanks.
No, on the contrary, you'll run into great problems. In Joshua Bloch's Effective Java, Item 74, he notes to implement Serializable judiciously, as it decreases the flexibility to change a class's implementation once its been released.
He specifically notes that "If you do not make the effort to design a custom serializable form, but merely accept the default, the serialized form will be forever tied to the class's original internal representation."
This is why you should have a serialVersionUID. It would be different between the two versions, and your code would know it can't be done, and stop the de-serializing.
If you remove fields from an object, then older objects will not deserialize. THe way to do this is to always use the same serialVersionUID and never remove fields, only add them.
精彩评论