Patrick Hughes
Patrick Hughes

Reputation: 357

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.

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.

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?

Upvotes: 0

Views: 2203

Answers (1)

uaarkoti
uaarkoti

Reputation: 3657

I am not sure I understand the question entirely but all the serialization logic definitely resides in the Object methods (readObject and 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.

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? 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?

You can learn more about Java Serialization here

Upvotes: 2

Related Questions