Saturday 23 November 2019

java - why user defined serialVersionUID is not used while desialization?



public class Employee2 implements java.io.Serializable {



private String name;

public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


}


i first serialized the Employee2 object.Then added one more field i.e age under Employee2. Now deserialize the Employee2 and get the below error




java.io.InvalidClassException: Test.Employee2; local class
incompatible: stream classdesc serialVersionUID = -342194960183674221,
local class serialVersionUID = -8890407383319808316





This is expected as structure of the class has been modified ( hence serialVersionUID got modified which is calculated internally at the time of serialization
and deserialization)



Now if i declare the below field under Employee2 and repeat the scenario, as per my understanding i should not get InvalidClassException because
serialVersionUID is same at the time of serialization and deserialization but still i am getting InvalidClassException exception. Why? If serialization
process still using serialVersionUID calculated at run time instead of manually defined under class then what is the use of declaring it?





static final Long serialVersionUID = 1L;



Answer



Look again. 'Long' isn't the same as 'long', and 1L isn't the same as -342194960183674221L, which is what is in the stream.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...