[英]What are the benefits/drawbacks to serializing a class in a fully serializable hierarchy, vs. Serializable child of non-serializable ancestry?
That is 那是
(1) (1)
class A B extends A C extends B D extends C E extends D implements Serializable
vs. 与
(2) (2)
A implements Serializable B extends A C extends B D extends C E extends D
(1)In the first case, serializing E will result in the state of E being saved, and A through D being reconstructed upon deserialization through a call to D's default constructor. (1)在第一种情况下,序列化E将导致保存E的状态,并且在反序列化时通过调用D的默认构造函数来重建A到D。
(2)In the second case, serializing E will result in the state of A through E all being saved, and no reconstruction required upon deserialization (since everything would be seriailizable due to inheriting from a serializable base class.) (2)在第二种情况下,对E进行序列化将保存A到E的状态,并且在反序列化时无需进行任何重构(因为由于从可序列化的基类继承而使得所有内容都可以序列化)。
Are there any dangers to doing it the first way? 第一种方法有任何危险吗? Would there be circumstances in which the savings of data transferred during serialization/deserialization by doing it the first way would be sufficient to make it a preferred approach, or is it always best to fully serialize the class hierarchy?
在某些情况下,通过第一种方法节省在序列化/反序列化过程中传输的数据是否足以使其成为首选方法,还是总是最好地完全序列化类层次结构?
Thanks in advance. 提前致谢。
It is not usually considered a best practice to implement Serializable
in a superclass, particularly if it is intended as a base class in a hierarchy of an exported API (however, your base class should be designed to anticipate subclasses that implement Serializable; see below). 通常不认为在超类中实现
Serializable
的最佳实践,尤其是在将其用作导出API的层次结构中的基类的情况下(但是, 应将基类设计为预期实现Serializable的子类;请参见下文)。 。 The reason is that it forces the clients of your API to make their subclasses serializable whether or not it useful for them to do so (Essential Java, 2nd Ed). 原因是,这会强制API的客户端使子类可序列化,无论它们对它们是否有用(Essential Java,第二版)。
The exception to this rule is when the base class itself participates in a framework for which Serializable
is necessary. 该规则的例外情况是基类本身参与了需要
Serializable
的框架。
Regardless, there are problems that can arise if a subclass is serializable and its parent isn't. 无论如何,如果子类可序列化而其父类不可序列化,则可能会出现问题。 In such a case the subclass is responsible for serializing and deserializing the state of its parent.
在这种情况下,子类负责序列化和反序列化其父级的状态。 The drawbacks are:
缺点是:
final
final
字段 Serializable
themselves require no-arg constructors Serializable
父类需要无参数构造函数 There is an excellent discussion of the pitfalls and recommended practices of serializing Java instances in Essential Java, 2nd Ed. 关于在Essential Java(第二版)中序列化Java实例的陷阱和建议的实践,进行了精彩的讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.