Class version problems in Java serialization Mechanism
Introduction
Some java classes that implement the serializable interface will see a static field named serialVersionUID. This article will fundamentally explain the meaning of this field.
Knowledge preparation
In java, class serialization and deserialization are implemented by jvm. Of course, different jvm may have different implementation methods. This article discusses the official jvm version of java.
After a class implements the serializable interface, it means that the developer allows this class to be serialized and deserialized, And the jvm is authorized to serialize and deserialize this class. If serializable is not implemented and class serialization is performed directly, the jvm reports an exception.
Serializable is an identity interface, and there is no method to implement.
Concept
Java serialization uses the long field named serialVersionUID to mark the version of the class. During Object serialization, Jvm writes the value of serialVersionUID to the serialized data of the class. During deserialization, JVM compares the serialVersionUID in the object data with the serialVersionUID of the local corresponding class, if the values are not the same (meaning the version of the class is different), an InvalidCastException is reported, that is, the class version does not match and cannot be deserialized. If the class version is the same, deserialization can be performed.
Value
There are two common serialVersionUID values:
One is a fixed long value, for example:
Private static final long serialVersionUID = 1L;
Private static final long serialVersionUID = 123L;
The second is to generate a 64-bit hash value based on the class name, Interface Name, member method, and attribute (ide can do this), for example:
Private static final long serialVersionUID = xxxxL;
When java. io. when the Class of the Serializable interface does not explicitly define a serialVersionUID value, the Java serialization mechanism will generate a serialVersionUID Based on the compiled Class for the serialization version comparison, once the class file changes (such as space and variable name), the serialVersionUID will also change.
The serialized data and the class version are the same, but the structure is different.
When a class has the same version as its serialized data (that is, the value of serialVersionUID is the same) but the class structure is different, the deserialization process follows the following rules.