Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Serial Version ID in Java? [duplicate]

Possible Duplicates:
Why should I bother about serialVersionUID?
what is a serial version id?

When i created a new class extending java.util.logging.Level in Eclipse, It asked me to add a default or generated serial version ID. I just added blindly without knowing what it is and why I have to add it.

Can anybody tell me what is it and why it its required.

like image 705
GuruKulki Avatar asked Feb 13 '10 19:02

GuruKulki


People also ask

What is 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 happens if two classes have same serialVersionUID?

Technically you can't prevent two classes from having the same serial version UID, much like you can't prevent two objects from having the same system hash code.

What does serialVersionUID 1l mean?

The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.

Why do you use serialVersionUID in a class?

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.


2 Answers

The Serial Version ID is used when serializing and deserializing an object. Java recognizes if the bytes you want to deserialize match the local class version. If not it will throw an exception.

This is important when doing RMI or persisting object structures.

There's a very good description about serializing in the javadoc of Serializable.

like image 175
tangens Avatar answered Sep 18 '22 01:09

tangens


It is the unique identifier for the class, used for serialization.

It is wise to declare it if you're serializing asap because if you don't declare one then when changing the class it will get a different one generated automatically and the serialization will stop working.

A good reference is here: http://c2.com/ppr/wiki/JavaIdioms/AlwaysDeclareSerialVersionUid.html

like image 43
metismo Avatar answered Sep 17 '22 01:09

metismo