Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will I be able to successfully deserialize a previous version of my class?

I have a class like this

class MyClass implements MyInterface, Serializable {
private static final serialVersionUID = 42;
...
}

interface MyInterface {
void A();
void B();
}

I have saved in a database some serialized instances of MyClass.

Now, I'm adding a new function to MyInterface so it becomes:

interface MyInterface {
void A();
void B();
void C();
}

And I have implemented C() in MyClass.

Will my previously serialized instances deserialize as the new class with no problem? I think yes but wanted to confirm, if possible, with explanation.

like image 720
Alexander Kulyakhtin Avatar asked Oct 02 '22 03:10

Alexander Kulyakhtin


2 Answers

Yes, there should be no problems with adding a new function, so long as the serialVersionUID stays the same, as Java only keeps information about fields when serializing an object.

From ObjectOutputStream:

State [of the serialized object] is saved by writing the individual fields to the ObjectOutputStream using the writeObject method…

like image 173
1000000000 Avatar answered Oct 13 '22 10:10

1000000000


If serialVersionUID is the same in the modified class serialization will try to do its best to deserialize data into the new class ignoring any differences.

like image 27
Evgeniy Dorofeev Avatar answered Oct 13 '22 11:10

Evgeniy Dorofeev