Java transient keyword is used in serialization to declare a variable when don’t want to serialize.
Note: Fields declare as static will also not serialize.
Pre-requisite:
For Example: In Employee Class fields age is declared with keyword transient. When you serialize the object of class Employee then values of age will not serialize and time of deserialization initialize with default value as per type.
import java.io.Serializable; public class Employee implements Serializable{ int id; String name; //This field will not be serialized transient int age; public Employee(int id, String name,int age) { this.id = id; this.name = name; this.age=age; } }
See Also:
- Java: static Serialization
- Java: Externalizable/Custom Serialization
- Java: Object Serialization with Inheritance
- Java: Object Externalizable Serialization with Inheritance
- Java: Array and Collection Serialization
- Java: Serialization Exception Handling
Serialization Example: with transient keyword
import java.io.FileOutputStream; import java.io.ObjectOutputStream; public class SerializationWithTransientExample { public static void main(String args[]) throws Exception { // creating employee object Employee e1 = new Employee(111, "Saurabh", 35); // writing object into employee file FileOutputStream f = new FileOutputStream("employee.txt"); ObjectOutputStream out = new ObjectOutputStream(f); // Serialize employee object as stream and write in file out.writeObject(e1); out.flush(); out.close(); f.close(); System.out.println("Employee object Serialize Successfully"); } }
Output
Employee object Serialize Successfully
Deserialization Example: with transient keyword
import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeserializationWithTransientExample { public static void main(String[] args) throws Exception { //Read object stream from file ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt")); //Deserialize object stream to employee object Employee e=(Employee)in.readObject(); System.out.println("Employee Detail :"); System.out.println("Id :"+e.id+"\nName: "+e.name+"\nAge: "+e.age); in.close(); } }
Output
Employee Detail :
Id :111
Name: Saurabh
Age: 0
As you can see, the printing age of the employee returns 0 as the default value for int type because the value of age was not serialized.
You must log in to post a comment.