Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 . Also see the related rule (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. :

Code Block
bgColor#FFCCCC

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

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

...

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

Code Block
bgColor#ccccff

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

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SER09-J

low Low

probable Probable

medium Medium

P4

L3

Related Guidelines

Secure Coding Guidelines for the Java Programming Language, Version 35.0

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

Bibliography

[API 20062014]

 

[Bloch 2008]

Item 17. , "Design and document Document for inheritance or else prohibit it Inheritance or Else Prohibit It"

[SCG 2009] 

 

...

Image Added Image Added Image Removed      Image Removed