Class members (static) cannot be serialized. The reason is obvious - they are not held by the object(s) of the class. Since they are associated with the class (rather than the object of that class), they are stored separately from the object.
serialVersionUID
is declared as a static field within a class that implements the java.io.Serializable
interface something like the following.
private static final long serialVersionUID = 1L;
It is used as a version control in a Serializable
class. If it is not explicitly declared, will be done automatically by JVM, based on various aspects of the Serializable
class, as described by the Java(TM) Object Serialization Specification.
If it is not explicitly declared within the class implementing the Serializable
interface then a warning may issue.
The serializable class
SomeClass
does not declare astatic
final
serialVersionUID
field of typelong
Is it serialized even though it is static
, how or is it an exception to serialization?
Serialization is done "magically," with lots of reflection, and has all sorts of special behavior -- including e.g. looking up the static
serialVersionUID
of the class.Think of
serialVersionUID
not as part of the object data being serialized but as part of the class description. The same way that the class name is part of the serialization stream. Full details of the stream format are documented at Grammar for the Stream Format.Let me clear you the use of
serialVersionUID
while writing and reading objects to/from file.In below code, I have written two functions
writeObject()
andreadObj()
writeObject()
is for writing the object in filereadObj()
is for reading the Object from fileHere I have used
serialVersionUID = 123L
for class B andserialVersionUID = 1L
for class A and also usedtransient
keyword for variable b in order to restrict to save the value of b into file.1) Write data to file then read the file you will get following output
you wil get value of b: 0 because we have used transient for b.
Now for testing try to write object by the same call but while reading change the
serialVersionUID = 765L
then u will get below exceptionSo, it is necessary to use same
serialVersionUID
while reading and writing the object from file.Also, it is used in RMI calls when you in-corporate classes from one machine to another machine or system.
The
serialVersionUID
itself is not serialized. At least, not in the same way as the other properties of your object. Instead it is written out to your output destination as part of a special 'header' that contains information required to rebuild the objects being written.