Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object serialization and deserialization when class field changed

Tags:

java

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 there is no exception thrown.

Thanks.

like image 676
Kai Avatar asked May 13 '26 19:05

Kai


2 Answers

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."

like image 81
Mike Avatar answered May 15 '26 07:05

Mike


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.

like image 20
bwawok Avatar answered May 15 '26 07:05

bwawok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!