Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would the Java compiler create a serialVersionUID synthetic field?

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.

like image 787
Jérôme Verstrynge Avatar asked Sep 12 '11 14:09

Jérôme Verstrynge


People also ask

What is the purpose of serialVersionUID in Java?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization. Specifying one gives more control, though JVM does generate one if you don't specify.

What is serialVersionUID and why do we need it?

Simply put, we use the serialVersionUID attribute to remember versions of a Serializable class to verify that a loaded class and the serialized object are compatible. The serialVersionUID attributes of different classes are independent. Therefore, it is not necessary for different classes to have unique values.

What should I set serialVersionUID to?

You should usually have the serialVersionUID as a private static final field in your class; you can choose any value. If you don't specify one, a value is generated automatically (this approach can lead to problems as it is compiler (object structure) dependent.

Is serialVersionUID mandatory in Java?

Defining a serialVersionUID field in a serializable class is not mandatory.


1 Answers

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.

like image 174
Vineet Reynolds Avatar answered Sep 23 '22 01:09

Vineet Reynolds