V6087. InvalidClassException may occur during deserialization.
The analyzer has detected a situation where the absence of an available default constructor during deserialization may lead to a 'java.io.InvalidClassException'.
When using the 'java.io.Serializable' interface, the JVM is in total control over serialization. When an object is getting deserialized, memory is allocated for it, and the object's fields are filled with the values from the byte stream without calling the constructor. It is important to remember that if a serializable class has a non-serializable parent, the deserialization mechanism will call the latter's default constructor. If there is no such constructor, a 'java.io.InvalidClassException' is thrown.
Consider the following contrived example:
class Parent {
private String parentField;
public Parent(String field) {
this.parentField = field;
}
// ....
}
class Child extends Parent implements Serializable {
public String childField;
public Child() {
super("");
}
public Child(String field1, String field2) {
super(field1);
this.childField = field2;
}
// ....
}
Since the parent class is not serializable, when deserializing the object of class 'Child', the built-in deserialization mechanism will attempt to call the default constructor and throw an exception if no such constructor is found.
For correct serialization, we only need to define an available default constructor in the parent class:
class Parent {
private String parentField;
public Parent() {
this.parentField = "";
}
public Parent(String field) {
this.parentField = field;
}
// ....
}
When implementing the 'java.io.Externalizable' interface, user-implemented logic is called: serialization and deserialization are implemented by overriding the methods 'writeExternal' and 'readExternal'. During deserialization, the default public constructor is always called first and only then is the 'readExternal' method called on the resulting object. If no such constructor exists, a 'java.io.InvalidClassException' will be thrown.
class Parent implements Externalizable
{
private String field;
public Parent(String field) {
this.field = field;
}
public void writeExternal(ObjectOutput arg0) throws .... {
// serializable logic
}
public void readExternal(ObjectInput in) throws .... {
// deserializable logic
}
// ....
}
This class has no appropriate constructor. An object of this class can be successfully serialized, but an attempt to restore a previously serialized object will result in throwing an exception.
To fix this, we only need to define an available constructor without parameters:
class Parent implements Externalizable
{
private String field;
public Parent() {
this.field = "";
}
public Parent(String field) {
this.field = field;
}
// ....
}