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 ie 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;
Look again. 'Long' isn't the same as 'long', and 1L isn't the same as -342194960183674221L, which is what is in the stream.
You are using Long
, the object type. You should be using long
, the primitive type, eg:
static final long serialVersionUID = 1L;
The UID is calculated dynamically at runtime only if it is not explicitly and properly declared.
Refer to Java Object Serialization Specification section 4.6.
An serialVersionUID is a hash of its originating class. If the class is updated, for example with different fields, the serialVersionUID can change. You have four (at least) possible courses of action:
Source :
http://www.coderanch.com/t/596397/java/java/private-static-final-long-serialVersionUID
链接地址: http://www.djcxy.com/p/23868.html上一篇: 所有类都有相同的串行版本ID?