Class SerializeTest , Here we serialize - deserialized the class.
Why
need to use ‘serialVersionUID’.
If you doesn’t write serialVersionUID
in your class if interface Serializable is implemented than Eclipse tool gives
warning
‘The
serializable class SerializeTest does not declare a static
final serialVersionUID field of type
long’
If you not add SerialVersionUID
for you class serialization runtime add Id with associate class.
By java doc
‘’ Note - It is strongly recommended
that all serializable classes explicitly declare
serialVersionUID
values, since the default serialVersionUID
computation is highly sensitive to class details that may vary depending on
compiler implementations, and can thus result in unexpected serialVersionUID
conflicts during deserialization,
causing deserialization to fail. ‘’
Now you understand why to add serialVersionUID
while creating Serializable class for persist.
For Test Create a class to Serialize and then read
the same class.
public class SerializeTest implements Serializable{
private static final long serialVersionUID = 1L;
private int test;
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
}
For
Writing a Serializable class
SerializeTest t = new SerializeTest();
t.setTest(10);
try {
OutputStream
file = new FileOutputStream("serializeTest.ser");
OutputStream
buffer = new BufferedOutputStream(file);
ObjectOutput
output = new ObjectOutputStream(buffer);
try {
output.writeObject(t);
}
finally {
output.close();
}
} catch (IOException
ex) {
ex.printStackTrace();
}
For
Reading a Serializable class
try {
InputStream file
= new
FileInputStream("serializeTest.ser");
InputStream
buffer = new BufferedInputStream(file);
ObjectInput
input = new ObjectInputStream(buffer);
try {
SerializeTest t = (SerializeTest)
input.readObject();
System.out.println("SerializeTest.test
: "+ t.getTest());
}
finally {
input.close();
}
} catch
(ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IOException
ex) {
ex.printStackTrace();
}
Expected Result is
SerializeTest.test : 10
Now, If you change the ‘serialVersionUID’
of class SerializeTest
another value like
private static final long serialVersionUID = 2L;
and now try to read the same
object using above read code.
You get the below result.
java.io.InvalidClassException: SerializeTest; local class
incompatible: stream classdesc serialVersionUID = 1, local class
serialVersionUID = 2