Serialization / Deserialization in Java
How to get value of transient field after deserialization?
- What is Transient in java?
Transient is used to the field members of a class turn off the serialization on these fields. To make field non serializable, we use transient keyword for that particular field. This is used if we do not need to make it persistent state of object ( no persist in database or file ).
@Transient
private String name;
- What if we need the value of transient field after deserialization?
If we simply de-serialize the object then we get default value as null of that transient field. See the following code snippet:
public class Employee implements Serializable{
private long empId;
private String empName;
@Transient
private transient String dept;
//getter settter
}
Serialization:
ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("fileName.txt"));
Employee emp = new Employee(); //normal instance
emp.setEmpId(2);
emp.setEmpName("Bikash");
emp.setDept("IT");
//writeReplace() is called before writeObject
oos.writeObject(emp);
oos.flush();
oos.close();
De-serialization:
ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("serialization.txt"));
Employee emp2 = (Employee)ois.readObject();
//after readObject is returned, readResolve() is called
System.out.println("Employee Id: "+emp2.getEmpId());
System.out.println("Employee Name: "+emp2.getEmpName());
System.out.println("Dept Name: "+emp2.getDept());
Output:
Employee Id: 2
Employee Name: Bikash
Dept Name: null
So, here dept was not persisted during serialization (it means dept is not serialized into bytestream).
After de-serialization, to get the value of transient field when it was serialized, we need to use readResolve() with singleton instance of that class.
public class Employee implements Serializable {
private static final long serialVersionUID = -5359502671506171397L;
private static Employee emp;
public static Employee getInstance(){
synchronized (Employee.class) {
if(emp == null){
emp = new Employee();
}
}
return emp;
}
protected Object readResolve(){
System.out.println("read resolve");
return emp;
}
private long empId;
private String empName;
private transient String dept;
//getter settter
}
Serialization:
ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("serialization.txt"));
Employee emp = Employee.getInstance(); //singleton instance
emp.setEmpId(2);
emp.setEmpName("Bikash");
emp.setDept("IT");
//writeReplace() is called before writeObject
oos.writeObject(emp);
oos.flush();
oos.close();
De-serialization:
ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("serialization.txt"));
Employee emp2 = (Employee)ois.readObject();
//after readObject is returned, readResolve() is called
System.out.println("Employee Id: "+emp2.getEmpId());
System.out.println("Employee Name: "+emp2.getEmpName());
System.out.println("Dept Name: "+emp2.getDept());
Output:
Employee Id: 2
Employee Name: Bikash
Dept Name: IT