Utsav Sharma
Utsav Sharma

Reputation: 49

Serialization : SerialVersion UID generation process

If we are transferring state of an object from machine A to machine B , then successful serialization/deserialization will only work if both the machines have same SerialVersion UID of the class to which the transferred object belongs to.

I want to know if the generation of serial version UID is done by JVM , then how do I ensure that it will be the same on both the machines A and B before initiating the serialization process ?

Upvotes: 0

Views: 64

Answers (2)

maurirlz
maurirlz

Reputation: 60

Question is asked in the Serialization documentation of Java, short answer, It is strongly recommended that you declare your own JVM serial number of type long static and final, if a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class.

JVM does the work of checking and ensuring your serialized object has the same UID as when it is de-serialized.

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Firstly, don't use Java Serialization. The only red highlighted text in the Secure Coding Guidelines for Java SE reads

Note: Deserialization of untrusted data is inherently dangerous and should be avoided.

To ensure the ID is the same define the serialVersionUID in the class.

@Serial private static final long serialVersionUID = 1L;

(@Serial is since the current version of Java, Java SE 14.)

To find the ID, first the serialVersionUID is looked for, and if not present it is calculated as specified in the docs (a hash of public methods and fields of the class).

Upvotes: 1

Related Questions