tiger
tiger

Reputation: 671

How serialversionuid is calculated

When I create Java Class in Eclipse which implements Serializable interface, I get a warning

The serializable class ABCD does not declare a static final serialVersionUID field of type long

So when I click on warning, I get a option in Eclipse to

Add generated Serial Version ID

Once I choose that option, Eclipse automatically creates a serialVersionUID variable for me.

Now I wanted to know that on what basis that number is generated. It is a just any random number ? Can I provide any random number of my own ?

Upvotes: 10

Views: 5247

Answers (2)

Bozho
Bozho

Reputation: 597036

It is calculated based on the structure of your class - fields, methods, etc. It is specified in the Object Serialization Specification - see this section for the exact format.

The spec describes what happens in no value is provided, but the autogeneration uses the same algorithm.

The sequence of items in the stream is as follows:

  • The class name.
  • The class modifiers written as a 32-bit integer.
  • The name of each interface sorted by name.
  • For each field of the class sorted by field name (except private static and private transient fields:
    • The name of the field.
    • The modifiers of the field written as a 32-bit integer.
    • The descriptor of the field.
  • If a class initializer exists, write out the following:
    • The name of the method, .
    • The modifier of the method, java.lang.reflect.Modifier.STATIC, written as a 32-bit integer.
    • The descriptor of the method, ()V.
  • For each non-private constructor sorted by method name and signature:
    • The name of the method, .
    • The modifiers of the method written as a 32-bit integer.
    • The descriptor of the method.
  • For each non-private method sorted by method name and signature:
    • The name of the method.
    • The modifiers of the method written as a 32-bit integer.
    • The descriptor of the method.

Upvotes: 16

andypandy
andypandy

Reputation: 1117

Automatically generated serialVersionIds are a hash based on the method signatures, parameters and such like in the class. It's done this way so that the serialVersionId will change whenever you change your class, indicating to the serialization mechanism that there data/class are no longer compatible. That's the default.

When you define your own, just start with 1, and increment when the class is no longer compatible with previously serialized data.

Upvotes: 4

Related Questions