java 序列化 内部类,序列化内部类实例

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值