java 规范说:“强烈建议所有可序列化类显式声明serialVersionUID 值,因为默认的serialVersionUID 计算对类详细信息高度敏感,而类详细信息可能会因编译器实现而异”
请问有人可以深入研究一下吗? getSerialVersionUID()方法进行了反射,并且反射在任何地方都常用,那么什么是编译器相关的?
最佳答案
J. Bloch 的书《Effective Java》对此问题给出了精彩的解释:
“第 74 项:明智地实现可序列化”:
If you do not specify this number explicitly by declaring a static final long field named serialVersionUID, the system automatically generates it at runtime by applying a complex procedure to the class. The automatically generated value is affected by the class’s name, the names of the interfaces it implements, and all of its public and protected members. If you change any of these things in any way, for example, by adding a trivial convenience method, the automatically generated serial version UID changes
UPD:评论中也有人问我为什么它依赖于编译器。实际上,这里的编译器依赖性与 getSerialVersionUID() 算法本身无关(当然,该方法在运行时调用),而是与类本身的描述方式有关。例如,一些合成方法可以在编译时添加到类中,这些方法也将计入 SUID 中。有关详细信息,请查看方法 ObjectStreamClass.computeDefaultSUID()
、它的作用以及如何计算默认 SUID。
关于java - 为什么依赖 ObjectStreamClass.getSerialVersionUID 不安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020845/