序列化 Java:哪些类需要“实现 Serializable"? [英] Serialization Java: which classes need to "implement Serializable"?
问题描述
所以我知道我最终可能会弄清楚,但我真的找不到可以回答这个看似简单的问题的主题.
so I know I could probably figure it out eventually, but I couldn't really find a topic that answers this seemingly simple question.
我正在序列化一组对象的向量,每个这样的对象都属于一个用户定义的类.我知道向量是可序列化的.我还必须使用户定义的类实现可序列化吗?而且,这些用户定义的类中的每一个都包含其他用户定义的类.那些也必须标记为实现 Serializable 吗?(等等,或者只是顶层类需要实现Serializable)?
I am serializing a vector of a set of objects, with each such object pertaining to one user-defined class. I know vectors are serializable. Do I also have to make the user-defined class implement serializable? And, each of these user-defined classes contains other user-defined classes. Do those have to be labeled as implementing Serializable as well? (and so on, or do just the top-level class need to implement Serializable)?
(忘记应该使用 arrayLists 而不是向量,我以前听说过,我正在练习,因为我听说向量适用于多线程.我找到了讨论类似内容的主题,但不完全是这个)
(Forget noting that arrayLists should be used instead of vectors, I've heard that before, I'm practicing because I hear vectors are good for multithreading. I found topics that discuss similar stuff, but not precisely this)
谢谢
推荐答案
是的,你说得对:任何被序列化的东西,包括字段(实例变量)引用的所有类,都必须实现 Serializable
,或字段必须是 transient
.
Yes, you are correct: Anything being serialized, including all classes referred to by fields (instance variables), must implement Serializable
, or the field must be transient
.
在您的情况下,用户定义的类必须实现 Serializable
,并且具有类型为 Serializable
的字段.这适用于递归,因此字段的类的字段也必须是Serializable
等
In your case, the user defined class must implement Serializable
, and have fields whose type is Serializable
. This applies recursively, so fields of the class of the fields must also be Serializable
, etc.
transient
关键字告诉序列化机制为了序列化的目的而忽略该字段.
The transient
keyword tells the serialization mechanism to ignore the field for the purposes of serialization.
这篇关于序列化 Java:哪些类需要“实现 Serializable"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!