Thursday, November 4, 2021

Transient and Serialization

 Learning Notes:

- Any variable/member is marked as "transient", then the content of this variable will not be serialized. It sets default values while serialization. 

public class Student implements Serializable { private static final long studentUID = -2936687026040726549L; private String studentName; private transient String subject; private transient int marks; // getters and setters 

} 

and creates a Student object with ("VRN", "Java", 85)

When we serialize this object using ObjectoutputStream and deserialize then the content of 'subject' variable will be null and 'marks' will be zero.


Note: Please note that when a variable is declared with final + transient: Behaviour will be the same. Means, while serialization value wont be written , while desrialization because there is no value the final value will be taken as default. 

private final String subject = "C++";

while seirialization the file will be written with NULL, but when we deserialize 'C++' will come as this is default value ( because of final )

--


So, while writing custom "serialization", we can declare that variable  as a transient and implement  customized writeObject and readObject functions. Use this functions while serializing/deserializing.


public class Student implements Serializable {

private transient Address address;

..

private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); oos.writeObject(address.getHouseNumber()); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); Integer houseNumber = (Integer) ois.readObject(); Address a = new Address(); a.setHouseNumber(houseNumber); this.setAddress(a);

}

}


courtesy: baeldung knowledge.

No comments:

Post a Comment