"An inner class is a nested class that is not explicitly or implicitly declared {{static}}" \[[JLS 2005|AA. Bibliography#JLS 05]\]. Serialization of inner classes (including local and anonymous classes) is error prone. According to the Serialization Specification \[[Sun 2006|AA. Bibliography#Sun 06]\]

Consequently, programs are forbidden to serialize inner classes.

Note, however, that none of the above issues apply to static member classes. Consequently, serialization of static member classes is permitted.

Noncompliant Code Example

In this noncompliant code example, the fields contained within the outer class are also serialized when the inner class is serialized.

public class OuterSer implements Serializable {
  private int rank;
  class InnerSer implements Serializable {
    protected String name;
    //...
  }
}

Compliant Solution

This compliant solution omits implementation of the Serializable interface in the InnerSer class.

public class OuterSer implements Serializable {
  private int rank;
  class InnerSer {
    protected String name;
    //...
  }
}

Compliant Solution

It is allowable to declare the inner class as static to prevent its serialization. It is also permissible for a static inner class to implement Serializable.

public class OuterSer implements Serializable {
  private int rank;
  static class InnerSer implements Serializable {
    protected String name;
    //...
  }
}

Risk Assessment

Attempts to serialize inner classes can introduce platform dependencies and can cause serialization of instances of the outer class.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

SER06-J

medium

likely

low

P18

L1

Automated Detection

Detection of inner classes that implement serialization appears to be straightforward.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

\[[API 2006|AA. Bibliography#API 06]\] 
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 74: "Implement serialization judiciously"
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 8.1.3, Inner Classes and Enclosing Instances|http://java.sun.com/docs/books/jls/third_edition/html/classes.html]
\[[Sun 2006|AA. Bibliography#Sun 06]\] "Serialization specification:  


SER05-J. Do not allow serialization and deserialization to bypass the Security Manager      16. Serialization (SER)      SER07-J. Make defensive copies of private mutable components