简体   繁体   English

java对象可以自行序列化吗?

[英]Can a java object serialize itself?

I have a JPanel that handles a bunch of settings that I would like to save and load by file name. 我有一个JPanel处理一堆我想保存和按文件名加载的设置。

It seems natural that since the panel already exists and knows all about itself that the load and save should be handled by the panel itself through a Save(String filename) and Load(String filename) actions attached to buttons. 看起来很自然,因为面板已经存在并且知道所有关于自身的负载和保存应该由面板本身通过附加到按钮的Save(String filename)和Load(String filename)动作来处理。

However all the serialization and/or persistence examples I find require an external overseer that passes the object into the serializer functions. 但是,我找到的所有序列化和/或持久性示例都需要一个将对象传递给序列化函数的外部监督器。

Can I simply serialize the panel object using something similar to writeObject(this) and this=readObject() or is there a standard way to do this that I haven't searched properly for? 我可以使用类似于writeObject(this)和this = readObject()的方法来序列化面板对象,还是有一种标准的方法来执行此操作我没有正确搜索?

I am not sure I understand the question entirely but all the serialization logic definitely resides in the Object methods (readObject and writeObject). 我不确定我是否完全理解了这个问题,但所有序列化逻辑肯定都存在于Object方法(readObject和writeObject)中。

When talking about who would invoke those methods, it all depends on your use case. 在谈论谁将调用这些方法时,这一切都取决于您的用例。 There are several reasons for serializing an object, like for ex: if one wants to pass the object across the wire to another JVM, or you want to persist the state of the object between JVM restarts, or any other use case where the entire state of the Object needs to be saved outside of the JVM its running in. 序列化对象有几个原因,比如ex:如果想要通过线路将对象传递给另一个JVM,或者你想在JVM重启之间保持对象的状态,或者整个状态的任何其他用例对象需要保存在其运行的JVM之外。

In your use case, can it be done? 在您的用例中,可以这样做吗? yes. 是。 Is that a good practice, maybe not. 这是一个好习惯,也许不是。 An abstraction is better because what if you have a need to persist other objects not accessible to JPanel? 抽象更好,因为如果你需要保留JPanel无法访问的其他对象呢? What if there is a need perform some other logic before serializing an object? 如果在序列化对象之前需要执行其他逻辑怎么办? What if there is a need for ordering or some other requirement that cannot be handle by your JPanel? 如果您的JPanel无法处理订购或其他要求,该怎么办?

You can learn more about Java Serialization here 您可以在此处了解有关Java序列化的更多信息

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

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