序列化会保存超类字段吗? [英] Will serialization save the superclass fields?

查看:63
本文介绍了序列化会保存超类字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的子类实现了 Serializable,但我的超类没有.

My subclass implements Serializable, but my superclass does not.

子类和超类都包含需要保存为子类状态的一部分的变量.

Both subclass and superclass contain variables that need to be saved as part of the state of the subclass.

序列化会保存超类字段吗?

Will serialization save the superclass fields?

推荐答案

如果不是 Serializable,则超类字段不能被序列化.这里总结了一些 Java 序列化规则:

A superclass fields cannot be serialized if it is not Serializable.Here is a summary of some rules of Java serialization:

一个对象是可序列化的(它本身实现了 Serializable 接口),即使它的超类不是.但是,可序列化类层次结构中的第一个超类,没有实现 Serializable 接口,必须有一个无参数构造函数.如果违反, readObject() 将产生一个 java.io.InvalidClassException 在运行时.

An object is serializable (itself implements the Serializable interface) even if its superclass is not. However, the firstsuperclass in the hierarchy of the serializable class, that does not implements Serializable interface, MUST have a no-arg constructor. If this is violated, readObject() will produce a java.io.InvalidClassException in runtime.

当对象被反序列化时,每个不可序列化的超类的无参数构造函数都会运行.但是,反序列化的对象呢?构造函数在反序列化时不会运行.

The no-arg contructor of every non-serializable superclass will run when an object is deserialized. However, the deserialized objects? constructor does not run when it is deserialized.

该类必须在序列化点可见.

The class must be visible at the point of serialization.

所有原始类型都是可序列化的.

All primitive types are serializable.

瞬态字段(带有瞬态修饰符)未序列化,(即,未保存或恢复).实现 Serializable 的类必须标记不支持序列化的类的瞬态字段(例如,文件流).

Transient fields (with transient modifier) are NOT serialized, (i.e., not saved or restored). A class that implements Serializablemust mark -transient fields of classes that do not support serialization (e.g., a file stream).

静态字段(带有静态修饰符)未序列化.

Static fields (with static modifier) are Not serialized.

如果可序列化对象的成员变量引用了不可序列化对象,则代码会编译但会抛出 RumtimeException.

If member variables of a serializable object reference to a non-serializable object, the code will compile but a RumtimeExceptionwill be thrown.

这篇关于序列化会保存超类字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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