private static final long serialVersionUID的作用
An SUID is not a hash of the object, but a hash of its originating class. If the class is updated, for example with different fields, the SUID can change. You have four (at least) possible courses of action:-
- 1: Leave out the SUID. This tells the runtime that there are no differences between versions of classes when serialising and deserialising.
- 2: Always write a default SUID, which looks like the heading of this thread. That tells the JVM that all versions with this SUID count as the same version.
- 3: Copy an SUID from a previous version of the class. That tells the runtime that this version and the version the SUID came from are to be treated as the same version.
- 4: Use a generated SUID for each version of the class. If the SUID is different in a new version of the class, that tells the runtime that the two versions are different and serialised instances of the old class cannot be deserialised as instances of the new class.
请不用简单地从别的网站复制粘贴(一针见血指出上面回答的缺点);这是对版权的破坏,而且这样的描述最多还是困惑读者。
SUID不是一个对象的哈希值(翻译错了,公司一个牛逼同事提醒了!),是源类的哈希值。如果类更新,例如域的改变,SUID会变化,这里有4个步骤:
1.忽略SUID,相当于运行期间类的版本上的序列化和反序列上面没有差异。
2.写一个默认的SUID,这就好像线程头部。告诉JVM所有版本中有着同样SUID的都是同一个版本。
3.复制之前版本类的SUID。运行期间这个版本和之前版本是一样的版本。
4.使用类每个版本生成的SUID。如果SUID与新版本的类不同,那么运行期间两个版本是不同的,并且老版本类序列化后的实例并不可以反序列成新的类的实例。
第四点才是private static final long serialVersionUID的作用的重点所在。

浙公网安备 33010602011771号