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.

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

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS