devxlogo

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”).

See also  How College Students Can Shape the Future of Tech Responsibility
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