Search code examples
javaserializationdeserializationserialversionuid

Java: serialize / deserialize failed because of `ClassNotFoundException`


I have a Pilot class, and an instance of that class: bobThePilot.

I serialize bobThePilot to a String and copy that to my my hard disk. Then I create a new project and recreate the Pilot class (exactly identical as before)....

And then I create newBobThePilot in this new project by de-serializing the String which I got from my disk. But it fails. Everybody said it was because of something named serialVersionUID.

Is it possible to do that (serialize and deserialize in different classes (although exactly identical class)? If so, how?

Thanks.

Morals:

  1. add serialVersionUID attribute to our serialized class Example:
    private static final long serialVersionUID = 1L;
  2. implements serializable to all classes which related to our serialized class


Solution

  • If you don't put a serial version id, the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class. Even though the classes are identical, different versions of the JDK can create different serialversionuids.