Developers may want to add some logic to handle deserialized objects before they are returned to the caller. This can be achieved by implementing
the readResolve
method.
Non-final classes implementing readResolve
should not set its visibility to private
as this would make it unavailable to
child classes. Instead, mark readResolve
as protected
, allowing it to be inherited.
Code examples
Noncompliant code example
public class Fruit implements Serializable {
private static final long serialVersionUID = 1;
private Object readResolve() throws ObjectStreamException // Noncompliant, `readResolve` should not be private
{...}
//...
}
public class Raspberry extends Fruit implements Serializable { // This class has no access to the parent's "readResolve" method
//...
}
Compliant solution
public class Fruit implements Serializable {
private static final long serialVersionUID = 1;
protected Object readResolve() throws ObjectStreamException // Compliant, `readResolve` is protected
{...}
//...
}
public class Raspberry extends Fruit implements Serializable { // This class has access to the parent's "readResolve"
//...
}