"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]:
- Serializing an inner class declared in a non-static context that contains implicit non-transient references to enclosing class instances results in serialization of its associated outer class instance.
- Synthetic fields generated by Java compilers to implement inner classes are implementation dependent and may vary between compilers; differences in such fields can disrupt compatibility as well as result in conflicting default
serialVersionUIDvalues. The names assigned to local and anonymous inner classes are also implementation dependent and may differ between compilers.
- Because inner classes cannot declare static members other than compile-time constant fields, they cannot use the
serialPersistentFieldsmechanism to designate serializable fields.
- Because inner classes associated with outer instances do not have zero-argument constructors (constructors of such inner classes implicitly accept the enclosing instance as a prepended parameter), they cannot implement
Externalizableinterface requires the implementing object to manually save and restore its state using the
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:
InnerSer class of this compliant solution deliberately fails to implement the
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.
Serialization of inner classes can introduce platform dependencies and can cause serialization of instances of the outer class.
Detection of inner classes that implement serialization is straightforward.
|"Serializable" inner classes of non-serializable classes should be "static"|
"Serializable" inner classes of "Serializable" classes should be static
Item 74, "Implement Serialization Judiciously"
Serialization Specification, Section 1.10, "The Serializable Interface"