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???
3 Answers 3
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.
6 Comments
serialVersionUID avoid the issue exactly?serialVersionUID is both static and final the deserialization will fail because the values of the field in class definition doesn't match the one in serialized object. This way the JVM can throw an exception instead of partially deserializing (or hyderating) an object.Employee class in future, should I change the serialVersionUID value? 2. Should the serialVersionUID values be different for different classes, eg. for Employee and Client?It's used for serialization, it should be declared in any class that implements Serializable.
It's effectively a version number the JVM can use to check if a serialized class matches the class definition you're trying to deserialize it into.
There's more information on it here: http://download.oracle.com/javase/1,5.0/docs/api/java/io/Serializable.html
Comments
It's to determine if they have serializable and deserializable compatibility if they have the same serialVersionUID and both implements Serializable then they are compatible.
And it's not limited to exceptions only as you will notice eclipse is prone to put a serialVersionUID early in your normal java class if it implements Serializable.
Edited: Updated to include @Spychos correct comment about the Serializable interface.
1 Comment
Explore related questions
See similar questions with these tags.
Exception, the answer is no, it can be used in any class.