JavaSe: Do not underestimate Serializable and javaseserializable
In Java, a class must support serialization. We usually implement Serializable. When using Serializable, A SerialVersionUID should be created to represent the version of the class. If this parameter is not specified, what will happen? Before learning about this, let's take a look at the exectpioon thread stack:
org.apache.catalina.session.StandardManager.startInternal Exception loading sessions from persistent storagejava.io.InvalidClassException: com.bes.webgate.vo.ActiveTransactionInfoVo; local class incompatiable: stream classdesc serial versionUID =4916958502461176947, local class serialversionUID = -5826417142685217629at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:1601)...at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)...at org.apache.catalina.session.StandardManager.load(StandardManager.java:162)...
From the exception above, there is a class incompatibility problem. Why?
Let's talk about the working mechanism of Serializable serialization:
During serialization, the system will write the serialVersionUID of the current class to the serialized file (or other intermediaries). During deserialization, the system will detect the serialVersionUID in the file, check whether it is consistent with the serialVersionUID of the current class. If it is consistent, the version of the serialized class is the same as that of the current class. In this case, deserialization can be successful, otherwise, it indicates that the current class has some transformations compared with the serialized class, such as the number of member variables and the type may change. In this case, an exception is thrown and deserialization fails.
How is the serialVersionUID generated and the generation rule?
By default, if the serialVersionUID attribute is not declared, the system calculates the hash value based on the member variables of the current class and assigns the value to the serialVersionUID. Therefore, the conclusion came out. Declare the serialVersionUID to avoid deserialization failures. For example, after a version upgrade, we may have deleted a member variable,
Some new member variables may also be added. At this time, our deserialization can still be successful, and the program can still restore data to the maximum extent. On the contrary, if serialVersionUID is not specified, the program will be suspended.
Of course, we also need to consider another situation. If the class structure changes unconventional, such as modifying the class name and type, even though the serialVersionUID verification has passed, however, the deserialization process will still fail, because the class structure has undergone devastating changes.