Tuesday 6 October 2015

How resolve java.io.InvalidClassException?

serialVersionUID and InvalidClassException

If serialVersionUid not defined in java class and there some change made before deserialization, it will throw InvalidClassException.

java.io.InvalidClassException: core.serialization.Employee;
local class incompatible: stream classdesc serialVersionUID = 7333563242382674116,
 local class serialVersionUID = -5668805012934441006
 at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:621)
 at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1623)
 at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)
 at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)
 at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
 at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
 at core.serialization.SerializationUtil.deserialize(SerializationUtil.java:19)

The reason is clear that serialVersionUID of the previous class and new class are different. Actually if the class doesn’t define serialVersionUID, it’s getting calculated automatically and assigned to the class.Java uses class variables, methods, class name, package etc to generate this unique long number.

Avoid InvalidClassException by using serialVersionUID:

Java Serialization permits some changes in the java class if they can be ignored. Some of the changes in class that will not affect the deserialization process are:

1.Adding new variables to the class.

2.Changing the variables from transient to non-transient, for serialization it’s like having a new field.

3.Changing the variable from static to non-static, for serialization it’s like having a new field.

But for all these changes to work, the java class should have serialVersionUID defined for the class.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...