"An inner class is a nested class that is not explicitly or implicitly declared static" [JLS 2015]. Serialization of inner classes (including local and anonymous classes) is error prone. According to the Serialization Specification [Sun 2006]:

Consequently, programs must not serialize inner classes.

Because none of these issues apply to static member classes, serialization of static member classes is permitted.

Noncompliant Code Example

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

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

Compliant Solution

The InnerSer class of this compliant solution deliberately fails to implement the Serializable interface:

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

Compliant Solution

If an inner and outer class must both be Serializable, the inner class can be declared static to prevent a serialized inner class from also serializing its outer class.

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

Risk Assessment

Serialization of inner classes can introduce platform dependencies and can cause serialization of instances of the outer class.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SER05-J

Medium

Likely

Medium

P12

L1

Automated Detection

Detection of inner classes that implement serialization is straightforward.

ToolVersionCheckerDescription
SonarQube
S2066
S2059
"Serializable" inner classes of non-serializable classes should be "static"
"Serializable" inner classes of "Serializable" classes should be static


Related Guidelines

MITRE CWE

CWE-499, Serializable Class Containing Sensitive Data

Bibliography

[API 2014]

Interface Externalizable
Interface Serializable

[Bloch 2008]

Item 74, "Implement Serialization Judiciously"

[JLS 2015]

ยง8.1.3, "Inner Classes and Enclosing Instances"

[Sun 2006]

Serialization Specification, Section 1.10, "The Serializable Interface"