Overriding Default Object Serialization

Normally, all that is required to perform serialization of an object is to implement the java.io.Serializable interface. However, in some cases, you may wish to control how an object is serialized instead of using the default mechanism. In other cases, you might simply want to add additional processing to the default mechanism. In these situations, you should add implementations of the readObject() and/or writeObject() methods to the class being serialized.

 import java.io.*;public class UserDef implements Serializable {	String userid;	transient String password;	//  transient, so not serialized	String fullName;	private void readObject(ObjectInputStream ois)				throws IOException, ClassNotFoundException {		userid = (String)ois.readObject();		fullName = (String)ois.readObject();		//	The above two lines are equivalent to adding:		//	ois.defaultReadObject();		password = "";	}  //  public void readObject()	private void writeObject(ObjectOutputStream oos)				throws IOException {		oos.writeObject(userid);		oos.writeObject(fullName);		//	The above two lines are equivalent to adding:		//	oos.defaultWriteObject();	}  //  public void writeObject()}  //  public class UserDef implements Serializable

Using these methods, you can control how the serialization and deserialization are performed. If you want to add functionality to the serialization process, you can allow the default mechanism to be used by calling the defaultReadObject() or defaultWriteObject() methods as mentioned in the sample code comments. After doing so, the desired behavior can be included in the appropriate method(s). This is demonstrated in the sample code’s readObject() method, where the password field is assigned an empty string value before the method returns.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: