为什么Java编译器会创建一个serialVersionUID合成字段?
作为调试应用程序的一部分,我注意到 Field.getDeclaredFields()
返回一些合成字段,包括扩展接口的类中的 serialVersionUID
字段,尽管没有扩展 可序列化
。
为什么编译器要添加这样的字段呢?
UPDATE
事实上,还创建了一个 $VRc
合成字段。
As part of debugging an application, I noticed that Field.getDeclaredFields()
returns some synthetic fields, including a serialVersionUID
field in a class extending an interface, although none extend Serializable
.
Why does the compiler add such fields?
UPDATE
In fact, there is also a $VRc
synthetic field created.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java编译器/运行时不会自动创建serialVersionUID字段。我怀疑您正在幕后使用某种形式的字节码增强框架,该框架被指示在运行时或编译期间添加合成字段。
$VRc
字段由 Emma 检测框架生成,因此这将是至少一个合成字段的原因。serialVersionUID
字段也是由 Emma 添加的,当instr.do_suid_compensation
属性设置为 true 时。The Java compiler/runtime will not automatically create a serialVersionUID field. I suspect that you are using some form of bytecode enchancement framework under the hood that is being instructed to add the synthetic fields either at runtime, or during compilation.
The
$VRc
field is produced by the Emma instrumentation framework, so that would be the reason for at least one of the synthetic fields.The
serialVersionUID
field is also added by Emma, when theinstr.do_suid_compensation
property is set to true.该字段对于 Java 序列化至关重要。简而言之:它允许 JVM 发现被序列化的类(例如保存在磁盘上)随后已被更改,并且无法安全地反序列化回对象。
看一下上面引用的文档中的版本控制章节,它解释了如何使用
serialVersionUID
。更新:刚刚注意到您的类没有实现
Serialized
。您确定没有超类或实现的接口不扩展Serialized
吗?This field is essential for Java serialization. In short: it allows the JVM to discover that the class that was serialized (e.g. saved on disk) has been changed afterwards and cannot be safely deserialized back to object.
Have a look at Version Control chapter in the document quoted above, it explains how
serialVersionUID
is used.UPDATE: just noticed your class does not implement
Serializable
. Are you sure none of super classes or implemented interfaces aren't extendingSerializable
?