序列化内部类实例 [英] Serializing a Inner Class instance

查看:150
本文介绍了序列化内部类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以序列化一个非静态内部类?

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.

内部类具有最终staic变量如何?

How about the inner class having final staic variable.

推荐答案

内部类包含对外部类的隐式引用,因此对于 一个可序列化的内部类及其外部类也必须如此.

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.

完全来自文档:

内部类的序列化(即,非内部类的嵌套类 静态成员类)(包括本地和匿名类)是 出于以下几个原因,我们强烈建议不要这样做.因为内在阶级 在非静态上下文中声明的变量包含隐式非瞬态 引用封闭的类实例,序列化这样的内部 类实例将导致其关联的外部序列化 类实例. javac(或其他)生成的合成字段 JavaTM编译器)实现内部类的实现 依赖并且在编译器之间可能有所不同;在这些领域的差异 可能会破坏兼容性并导致默认冲突 serialVersionUID值.分配给本地和匿名的名称 内部类也依赖于实现,并且之间可能有所不同 编译器.由于内部类不能声明其他的静态成员 比编译时常量字段,它们不能使用 serialPersistentFields机制来指定可序列化的字段. 最后,因为与外部实例相关联的内部类不 具有零参数构造函数(此类内部类的构造函数 隐式接受封闭的实例作为前置参数), 他们无法实现可外部化.上面没有列出任何问题, 但是,适用于静态成员类.

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.

所以

因为在非静态上下文中声明的内部类包含隐式 对封装类实例的非临时引用,进行序列化 这样的内部类实例将导致其内部序列化 关联的外部类实例.

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.

来源

这篇关于序列化内部类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆