BOSS
BOSS

Reputation: 2951

Serializing a Inner Class instance

Is it possible to serialize a non Static Inner class?

If yes can you provide a good example.

I googled through few blogs and sites non of answer convinced me.

EDIT: How about the inner class having final staic variable.

Upvotes: 0

Views: 2080

Answers (1)

Simon Dorociak
Simon Dorociak

Reputation: 33505

Inner class contains an implicit reference to the outer class, so for an inner class to be serializable its outer class must be as well.

Exactly from docs:

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged for several reasons. Because inner classes declared in non-static contexts contain implicit non-transient references to enclosing class instances, serializing such an inner class instance will result in serialization of its associated outer class instance as well. Synthetic fields generated by javac (or other JavaTM 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 serialVersionUID values. The names assigned to local and anonymous inner classes are also implementation dependent and may differ between compilers. Since inner classes cannot declare static members other than compile-time constant fields, they cannot use the serialPersistentFields mechanism to designate serializable fields. Finally, 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 Externalizable. None of the issues listed above, however, apply to static member classes.

So

Because inner classes declared in non-static contexts contain implicit non-transient references to enclosing class instances, serializing such an inner class instance will result in serialization of its associated outer class instance as well.

Source

Upvotes: 8

Related Questions