How serialversionuid is calculated

When I create a Java class in Eclipse that implements the Serializable interface, I get a warning

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

So when I click on the warning, I get an option in Eclipse for

Add Generated Serial Version Identifier

As soon as I select this option, Eclipse will automatically create the variable serialVersionUID for me.

Now I wanted to know on what basis this number was generated. Is this just a random number? Can I provide any random number?

+6
source share
2 answers

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

The specification describes what happens without value, but auto-generation uses the same algorithm.

The sequence of elements in the stream is as follows:

  • Class name.
  • 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: * Field name. * Field modifiers written as a 32-bit integer. * Field descriptor.
  • If a class initializer exists, write the following: * The name of the method. * Method modifier, java.lang.reflect.Modifier.STATIC, written as a 32-bit integer. * method handle, () V.
  • For each non-private constructor, sorted by method name and signature: * Method name. * Modifiers method written as a 32-bit integer. * Method handle.
  • For each non-private method, sorted by method name and signature: * Method name. * Method modifiers written as a 32-bit integer. * Method handle.
+12
source

Automatically generated serialVersionIds are hashes based on method signatures, parameters, etc., similar to a class. This was done so that serialVersionId changes whenever you change your class, indicating the serialization mechanism that the data / class is no longer compatible. This is the default value.

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

+4
source

Source: https://habr.com/ru/post/899116/


All Articles