简体   繁体   English

Java:哪些类必须实现Serializable

[英]Java: Which classes have to implement Serializable

I am currently trying to learn and understand how to store data from user input as a file. 我目前正在尝试学习和了解如何将用户输入的数据存储为文件。

Currently, I have the classes "movies" and "series" and the class "MediaLibrary". 目前,我有“电影”和“系列”课程以及“MediaLibrary”课程。

Now's the question: Which classes have to implement Serializable? 现在的问题是:哪些类必须实现Serializable?

Do I only have to implement it at MediaLibrary (since I store objects from the other classes in ArrayList's) or do the other classes need Serializable too? 我只需要在MediaLibrary上实现它(因为我存储了ArrayList中其他类的对象),还是其他类也需要Serializable?

Thanks for your help. 谢谢你的帮助。

LevKaz LevKaz

EDIT 1: What makes my question unique from the possible duplicate? 编辑1: 是什么让我的问题与可能的重复有关? In the possible duplicate the guy asked, why not all objects are serializable , since he doesn't wanted to write it in every single class. 在可能的重复中,这个人问, 为什么不是所有对象都是可序列化的 ,因为他不想在每个类中编写它。 I wanted to know (and understand) if it would be enough to serialize one class which is holding other objects, or if all objects have to implement the serializable interface. 我想知道(并理解)是否足以序列化一个持有其他对象的类,或者所有对象是否必须实现可序列化接口。

Hopefully I showed up the difference of my question to the one I got suggested by Ali Seyedi. 希望我把我的问题与Ali Seyedi建议的问题区别开来。

If you want it to work by just writing implements Serializable , then all of the classes will need to be Serializable , because otherwise an exception will be thrown when attempting to serialize the ArrayList . 如果你想通过编写implements Serializable来工作,那么所有的类都需要是Serializable ,因为否则在尝试序列化ArrayList时会抛出异常。

You could avoid making movies and series Serializable by writing writeObject in such a way that instead of writing movies and series objects to the ObjectOutputStream , you write their fields directly. 可以通过编写writeObject 避免制作moviesseries Serializable ,以便不是将moviesseries对象写入ObjectOutputStream ,而是直接编写它们的字段。 However, you should not adopt such an approach unless you have very good reason to do so. 但是,除非你有很好的理由这样做,你不应该采取这样的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM