Why would the Java compiler create a serialVersionUID synthetic field?
Asked Answered
F

2

10

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.

Forefinger answered 12/9, 2011 at 14:17 Comment(1)
Which compiler are you using?Anabelle
O
11

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 the instr.do_suid_compensation property is set to true.

Ornstead answered 12/9, 2011 at 14:42 Comment(2)
You are right, I am indeed using Emma for test coverage. When I disactivate it, the fields are not there anymore.Ironwork
Yes, even serialVersionUID is also generated by Emma if a certain property was set.Ornstead
S
1

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 extending Serializable?

Sarcomatosis answered 12/9, 2011 at 14:21 Comment(2)
I think the question is more about why the field got added when none of the classes in the inheritence hierarchy implement the Serializable interface, not what the purpose of the field is.Anabelle
Yes, 100% sure. It is similar to class A implements B and B is declared as an interface. A and B don't declare any fields themselves. That's it.. (and no, this is not about the meaning/use of serial version UIDs)Ironwork

© 2022 - 2024 — McMap. All rights reserved.