Serialization of objects and deserialization when changing a class field

I have a question about serializing and deserializing objects when changing a class field.

If an object of type MyClass

MyClass {
    String str1;
    LinkedList mylist = new LinkedList();
    String str2;

}

was serialized to a file.

Then I changed the code that changed the definition of MyClass to

MyClass {
    String str1;
    LinkedList mylist = new LinkedList();
    Map myMap = new HashMap();

}

After that, I will deserialize the object from the file to the MyClass object using the modified code. This is normal? Will any exceptions be thrown during deserialization? I want to reuse an old object. That is, I want de-serialization to be possible. Therefore, I hope that there will be no exceptions.

Thank.

+3
source share
3 answers

, , . Joshua Bloch Java, . 74, , Serializable, .

, " , , ".

+4

serialVersionUID. , , , , -.

+2

If you remove fields from an object, old objects will not be deserialized. The way to do this is to always use the same serialVersionUID and never delete fields, only add them.

+2
source

Source: https://habr.com/ru/post/1765733/


All Articles