Invoking overridable methods from the readObject() method can allow the overriding method to read the state of the subclass before it is fully constructed, because the base class is deserialized first, followed by the subclass. As a result, readObject() must not call any overridable methods.
Also see the related rule MET06-J. Do not invoke overridable methods in clone().
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() {
// ...
}
|
This compliant solution removes the call to the overridable method. When removing such calls is infeasible, ensure that the method is declared private or final.
private void readObject(final ObjectInputStream stream) throws
IOException, ClassNotFoundException {
stream.defaultReadObject();
}
|
*SER09-EX0:* The {{readObject()}} method may invoke the overridable method {{java.io.ObjectInputStream.defaultReadObject()}} \[[SCG 2009|AA. Bibliography#SCG 09]\]. |
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 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Guideline 4-4 Prevent constructors from calling methods that can be overridden |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="bba5e58f-5b0a-4184-b613-dbe0e39ee5ff"><ac:plain-text-body><![CDATA[ |
[[API 2006 |
AA. Bibliography#API 06]] |
|
]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3e88ab04-eb3d-4d42-a7a2-02a29239a86c"><ac:plain-text-body><![CDATA[ |
[[Bloch 2008 |
AA. Bibliography#Bloch 08]] |
Item 17: "Design and document for inheritance or else prohibit it" |
]]></ac:plain-text-body></ac:structured-macro> |