devxlogo

Customizing Serialization

Customizing Serialization

If a class contains non-serializable variables, and you need to preserve the state of those variables, you will have to customize the default serialization behavior of the class. You can achieve this by providing an implementation for the readObject() and writeObject() methods in the class. These implementations should manually serialize and deserialize the non-serializable objects. If a class provides an implementation for these methods, the ObjectOutputStream and ObjectInputStream used to read write and read objects of that class will call these methods. For example, consider the TestSerialization class from the Tip “Watch Out for the NotSerializableException”. In a new definition, you will add these methods.

 1.     public void writeObject (ObjectOutputStream out)2.       throws IOException {3. 4.       out.defaultWriteObject();5. 	   out.writeObject(o_.getStr());6.     }7. 8.      public void readObject (ObjectInputStream in) 9.          throws IOException, ClassNotFoundException {10. 	11.    in.defaultReadObject();12.    String str = (String)(in.readObject());13.    this.o_ = new NonSerializableObject(str);14. }

On Line 4, in the method writeObject, you call the method defaultWriteObject(). This method writes out all the non-transient fields. On Line 5, you write out the object o of type NonSerializableObject. Thus, the transient fields will have to be written out separately. Similarly, on Line 11, in the method readObject, the method defaultReadObject reads in the non-transient fields. You read in the transient field on Line 12 and assign it to the object on Line 13.

See also  5 Tips for Working With an Onsite Interpreter
devxblackblue

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