Sunday, 21 September 2014

Transient keyword

Serialization is the process of converting object state into sequence of bytes. de-Serialization is a process to bring back the object’s state from bytes. if you don't want to serialize particular field, then make that field as transient.

import java.io.*;

public class Employee implements Serializable{
    int id;
    String firstName;
    transient String lastName;
    
    Employee(int id, String firstName, String lastName){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public static void main(String args[]) throws Exception{
        
        /* Serialize object */
        FileOutputStream fos = new FileOutputStream("ser.out");
        ObjectOutputStream out = new ObjectOutputStream(fos);
        Employee emp = new Employee(1, "Krishna", "Arjun");
        out.writeObject(emp);
        
        /* Deserialize object */
        FileInputStream fis = new FileInputStream("ser.out");
        ObjectInputStream in = new ObjectInputStream(fis);
        Employee emp1 = (Employee)in.readObject();
        
        System.out.println(emp1.id + " " + emp1.firstName +" " +emp1.lastName);
    }
}

Output
1 Krishna null


In the above program,

int id;
String firstName;
transient String lastName;

lastName is declared using the transient keyword, so it is not eligible for serialization. So when we print the Employee 'emp1', it prints null for lastName.
                                                             Home

No comments:

Post a Comment