Reputation: 1804
class MyClass implements Serializable{}
What must I write so that the Object knows when it is getting serialized and deserialized to do something before getting serialized and after getting deserialized?
Upvotes: 0
Views: 342
Reputation: 85779
You can use readObject
and writeObject
methods for this purpose. writeObject
method will be executed when serializing your object reference.
Basically, you will do it like this:
public class MyClassToSerialize implements Serializable {
private int data;
/* ... methods ... */
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWrite(); //serialization of the current serializable fields
//add behavior here
}
}
More info on the usage of these methods: http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serialTOC.html
Upvotes: 2