The role of java serialVersionUID and why it is 1

Literally: Serial version UID 

That is to say serialVersionUID is the version number of the class

- The class is identified by the class name, and a few fields are added but still the same class name, it is necessary to distinguish it by the version number

 

(1) One effect is to refuse to deserialize the old value

Suppose I serialize a value when I have 10 fields. Now I have changed to 20 fields, and after changing the version number, I can refuse to serialize the previous value (deserialization error)

-- what's the point? For example, my 20 fields must have values, or the default values ​​are weird. In this case, the old value field is not enough, and it is naturally not allowed to deserialize it.

 

 

The first usage, you need to generate a corresponding unique version number every time you change the field. The virtual machine already does this by default. If necessary, just don't assign a value and let the virtual machine assign it.

(2) The second function is to force the deserialization of the old value

Suppose I serialize a value when I have 10 fields. Now I changed to 20 fields, I still use the same version number, you can force the deserialization of the previous value

 

 

In terms of two usages, the second is counter-intuitive, but I'm afraid it is the more common practice.

 

 

 

Write the value as 1, and you can change it to 2, 3, .... It has a sense of increment, which looks more like a version number. In addition, it is possible to use 1 for all classes, and there will be no conflicts between classes.

- Why not use 0, the version is 0, weird

- Why don't you use negative numbers? It's even stranger

There is also a series of numbers that imitate the practice of virtual machines.

Guess you like

Origin blog.csdn.net/u013595395/article/details/113804679