Invoking overridable methods from the readObject()
method can cause the overriding method to read the state of the subclass before it is fixed. This is because the base class is deserialized first, followed by the subclass. Also see the related guideline MET07-J. Do not invoke overridable methods on the clone under construction.
Noncompliant Code Example
This noncompliant code example invokes an overridable method from the readObject()
method.
Code Block | ||
---|---|---|
| ||
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. If this cannot be done, ensure that the overridable method is declared private
or final
.
Code Block | ||
---|---|---|
| ||
private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); } |
Exceptions
Wiki Markup |
---|
*EX1:* "The {{readObject}} methods will usually call {{java.io.ObjectInputStream.defaultReadObject}}, which is an overridable method." \[[SCG 2009|AA. Java References#SCG 09]\]. |
Risk Assessment
Invoking overridable methods from the readObject()
method can lead to initialization errors.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
SER11- J | low | probable | medium | P4 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 2006|AA. Java References#API 06]\] \[[SCG 2009|AA. Java References#SCG 09]\] Guideline 4-4 Prevent constructors from calling methods that can be overridden \[[Bloch 2008|AA. Java References#Bloch 08]\] Item 17: "Design and document for inheritance or else prohibit it" |
SER10-J. Do not serialize direct handles to system resources 18. Serialization (SER) SER12-J. Avoid memory and resource leaks during serialization