Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically execute a method after deserialization?

Tags:

I've got a class Foo, it's Serializable. It represents a graphical object, and I want it to restore its handles to the state before serializing. All data is stored within the object, I just need a method to be called in the right moment. How can I achieve it? Is this possible in Java?

(I have my Foos in a List in Bar object, and in some other places - that's why I don't want to do it manually.)

like image 822
mik01aj Avatar asked Jul 27 '10 11:07

mik01aj


People also ask

Which method is used for deserialization?

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class. We must have to implement the Serializable interface for serializing the object.

What is Ysoserial?

ysoserial is a collection of utilities and property-oriented programming "gadget chains" discovered in common java libraries that can, under the right conditions, exploit Java applications performing unsafe deserialization of objects.

What happens when you serialize and deserialize an object?

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.


1 Answers

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

 private void readObject(java.io.ObjectInputStream in)      throws IOException, ClassNotFoundException; 

Implement this method, and call in.defaultReadObject(), and then do whatever custom logic you want.

Check the docs of java.io.Serializable for more details

like image 85
Bozho Avatar answered Oct 06 '22 02:10

Bozho