Avoid Serialization Using the Transient Modifier

Avoid Serialization Using the Transient Modifier

One of the less commonly used keywords in the Java language is transient. The transient modifier came into effect in JDK 1.1. It indicates a field that is not a part of the object’s persistent state. Hence, declaring a variable as transient prevents it from being serialized. If the NotSerializableObject declared in the Tip “Watch Out for the NotSerializableException” does not need to be serialized, you can change the class that uses its instance to:

 1. public class TestSerializable implements Serializable {2.   public String s = "Hello";3.   public transient NonSerializableObject o = new4.                                     NonSerializableObject(s);	5. }

The transient modifier is now used to qualify the object o. As a result, when the writeObject() method is used for an object of the type TestSerializable, the object o is not saved along with the object. If you need to preserve the state of the object o, then you will have to customize how you serialize objects of type TestSerializable (see Tip “Customizing Serialization”).


Share the Post: