please help clarifying the doubt :
While doing serialization, if we have defined the version id as
static final long serialVersionUID = 2L;
, and since this being static开发者_StackOverflow中文版 it should not get serialize while storing the object to the persistent medium.
While reading the object back from persistent medium, how does the object match the versionID since the de serialized object should not contain it.
The serialization runtime adds the class's serialVersionUID
to the object stream automatically, it's not treated like a "normal" instance field. This all happens under the covers.
serialVersionUID is an exception to the rule that “static fields don’t get serialized”. ObjectOutputStream writes every time the value of serialVersionUID to the output stream. ObjectInputStream reads it back and if the value read from the stream does not agree with the serialVersionUID value in the current version of the class, then it throws the InvalidClassException. Moreover, if there is no serialVersionUID officially declared in the class to be serialized, compiler automatically adds it with a value generated based on the fields declared in the class.
Refer: http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html
精彩评论