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:

  • Leave out the serialVersionUID. This tells the runtime that there are no differences between versions of classes when serialising and deserialising.
  • Always write a default serialVersionUID, which looks like the heading of this thread. That tells the JVM that all versions with this serialVersionUID count as the same version.
  • Copy an serialVersionUID from a previous version of the class. That tells the runtime that this version and the version the SUID came from are to be treated as the same version.
  • Use a generated serialVersionUID for each version of the class. If the serialVersionUID is different in a new version of the class, that tells the runtime that the two versions are different and serialised instances of the old class cannot be deserialised as instances of the new class.
  • Source :

    http://www.coderanch.com/t/596397/java/java/private-static-final-long-serialVersionUID

    链接地址: http://www.djcxy.com/p/23868.html

    上一篇: 所有类都有相同的串行版本ID?

    下一篇: 为什么用户定义的serialVersionUID在去电时不使用?