What is serialVersionUID?

What is serialVersionUID for?

Java's serialization mechanism verifies the version by judging the serialVersionUID of the class at runtime 一致性.
When deserializing, the JVM will compare the serialVersionUID in the incoming byte stream with the serialVersionUID of the corresponding local entity (class). If they are the same, they are considered consistent and can be deserialized, otherwise there will be serialization Inconsistent version exception.


Why is the value of the specified serialVersionUID displayed?

If the specified serialVersionUID is not displayed, the JVM will automatically generate a serialVersionUID when serializing 根据属性, and then serialize together with the attributes before persistence or network transmission. When deserializing, the JVM will automatically 根据属性generate a new version of serialVersionUID, and then compare this new version of serialVersionUID with the old version of serialVersionUID generated during serialization. If they are the same, the deserialization is successful, otherwise an error will be reported.
If the display is specified, the JVM will still generate a serialVersionUID during serialization and deserialization, but the value is displayed for us 指定的值, so that the old and new versions of the serialVersionUID will be consistent during deserialization.


serialVersionUID is also static modified, why serialVersionUID will be serialized?

In fact, the serialVersionUID attribute 没有is serialized, and the JVM will have a serialVersionUID when serializing the object, and then we will display the serialVersionUID automatically generated by 自动生成the value of the specified serialVersionUID attribute .赋给


In actual development, what problems will occur if the specified serialVersionUID is not displayed?

Of course there will be no problem if our class is not modified after it is written.
But this is impossible in actual development, our class will continue to iterate, once the class is verified 不兼容性修改, it will be verified during deserialization, and if it is not clearly defined, 根据类名及属性等a serialVersionUID will be automatically generated, and the two serialVersionUIDs are different It will report an error. So in actual development, we will specify a serialVersionUID explicitly, it doesn't matter what the value is, as long as it remains unchanged.


When is serialVersionUID modified?

The "Alibaba Java Development Manual" has the following provisions:
insert image description here
Why Alibaba requires programmers to carefully modify the value of the serialVersionUID field

Guess you like

Origin blog.csdn.net/weixin_37646636/article/details/132129193