Overriding Default Object Serialization

Overriding Default Object Serialization

Normally, all that is required to perform serialization of an object is to implement the 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*;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.

See also  How College Students Can Shape the Future of Tech Responsibility

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist