序列化对象为什么需要定义serialVersionUID值?
首先,我们先来看看源码是怎么描述的?
The serialization runtime associates with each serializable class a version
number, called a serialVersionUID, which is used during deserialization to
verify that the sender and receiver of a serialized object have loaded
classes for that object that are compatible with respect to serialization.
If the receiver has loaded a class for the object that has a different
serialVersionUID than that of the corresponding sender's class, then
deserialization will result in an {@link InvalidClassException}.
大概意思是:
序列化运行时与每个可序列化类关联一个版本号,称为 serialVersionUID,在反序列化期间使用该版本号来验证序列化对象的发送方和接收方是否已加载与序列化兼容的该对象的类。
如果接收者为对象加载了一个类,该对象的 serialVersionUID 与相应发送者的类不同,则反序列化将导致 {InvalidClassException}。
总结如下:
- SerialVersionUid 是为了序列化对象版本控制,告诉 JVM 各版本反序列化时是否兼容
- 如果在新版本中这个值修改了,新版本就不兼容旧版本,反序列化时会抛出InvalidClassException异常
- 仅增加了一个属性,希望向下兼容,老版本的数据都保留,就不用修改
- 删除了一个属性,或更改了类的继承关系,就不能不兼容旧数据,这时应该手动更新 SerialVersionUid