The readObject() method must not call any overridable methods. Invoking overridable methods from the readObject() method can provide the overriding method with access to the object's state before it is fully initialized. This premature access is possible because, in deserialization, readObject plays the role of object constructor and therefore object initialization is not complete until readObject exits (see also MET06-J. Do not invoke overridable methods in clone()).

Noncompliant Code Example

This noncompliant code example invokes an overridable method from the readObject() method:

private void readObject(final ObjectInputStream stream)
                        throws IOException, ClassNotFoundException {
  overridableMethod(); 
  stream.defaultReadObject();
}

public void overridableMethod() {
  // ...
}

Compliant Solution

This compliant solution removes the call to the overridable method. When removing such calls is infeasible, declare the method private or final.

private void readObject(final ObjectInputStream stream)
                        throws IOException, ClassNotFoundException {
  stream.defaultReadObject();
}

Exceptions

SER09-J-EX0: The readObject() method may invoke the overridable methods defaultReadObject() and readFields() in class java.io.ObjectInputStream [SCG 2009].

Risk Assessment

Invoking overridable methods from the readObject() method can lead to initialization errors.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SER09-J

Low

Probable

Medium

P4

L3

Automated Detection

ToolVersionCheckerDescription
Parasoft Jtest

2024.1

CERT.SER09.VREADOBJDo not invoke overridable methods from the readObject() method

Related Guidelines

Secure Coding Guidelines for Java SE, Version 5.0

Guideline 7-4 / OBJECT-4: Prevent constructors from calling methods that can be overridden

Bibliography

[API 2014]


[Bloch 2008]

Item 17, "Design and Document for Inheritance or Else Prohibit It"

[SCG 2009]



3 Comments

  1. I have a question, 
    If I change execution order like this:
     stream.defaultReadObject();
     overridableMethod();
    is not violate this rule?
    1. Yes. In theory, your code sample would violate the rule. (In practice, it might be safe if stream.defaultReadObject() initializees the this object.) Such overridable methods must not be invoked until the object has been fully initialized.

  2. Automated Detection?