简体   繁体   中英

Serialization of static inner class

Can we serialize a static inner class in Java? The class itself is declared as static here.

A static inner class is no different than a top-level class in this respect: it can be serialized if it is declared to implement Serializable (or is a subclass of a class declared to implement Serializable ). Also, as with top-level classes, all objects encountered during serialization at run time must be serializable to avoid a NotSerializableException . Since the inner class is static , the nature of the outer class is irrelevant to this.

@Tinkerbel something to note -

Serializing static nested classes is fine but when (in future) if static inner classes are ever moved to a different outer class then de serializing the old objects is a problem.

All the fields are assigned to be default/null.

It seems the answer may vary by Java version now.

The serialization spec in JDK 7 says:

Note - Serialization of inner classes (ie, 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.

and from experience serializing objects between the Oracle and IBM JDK 1.7 versions, I can tell you that it doesn't always work. I can't say for sure it always fails, but you sure can't count on it working.

The code path that is not failing in my app worked fine on JDK 1.5 for 5 years in production and I see nothing in previous documentation on serialization resembling the current statement. So, it seems the Java gods have is allowed this code pattern in JDK 7.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM