Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is serialVersionUID in java, normally in exception class? [duplicate]

Possible Duplicate:
Why should I bother about serialVersionUID?

I am going through some exception handling code and i saw something named as serialVersionUID. What this uid is for?? Is it only limited to exception or can be used in all classes??? what is the advantage of this id???

like image 372
amod Avatar asked Aug 25 '11 08:08

amod


People also ask

What is serialVersionUID exception class?

The serialization at runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.

What is serialVersionUID used for 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.

Can 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 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.


1 Answers

serialVersionUID is a field to define the version of a particular class while seriializing & deseriializing.. consider a scenario where you have a class Employee which has 3 fields which has been in production for some time (meaning there may exist many serialized versions of employee objects), when you update the class to include (say a 4th field) then all the previous class (which are serialized) cannot be casted or de-serialized to the new one & you'll get an exception.

to avoid this issue, you can use the serialVersionUID field to tell JVM that the new class is in fact of a different version (by changing the serialVersionUID).

@Farmor & @Tom Jefferys said pretty much the same thing, but with an example things look a lot simpler.

like image 158
Anantha Sharma Avatar answered Sep 29 '22 00:09

Anantha Sharma