When you want to store the transient variables state as a part of the serialized object at the time of serialization the class must implement the following methods –
The normal serializable variables are saved and restored by calling defaultWriteObject() and defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization process for the object to be saved or restored respectively.
private void wrtiteObject(ObjectOutputStream outStream)
{
//code to save the transient variables state as a part of serialized object
} private void readObject(ObjectInputStream inStream)
{
//code to read the transient variables state and assign it to the de-serialized object
}
e.g.{
//code to save the transient variables state as a part of serialized object
} private void readObject(ObjectInputStream inStream)
{
//code to read the transient variables state and assign it to the de-serialized object
}
public class TestCustomizedSerialization implements Serializable{
private static final long serialVersionUID =-22L;
private String noOfSerVar;
transient private int noOfTranVar;
TestCustomizedSerialization(int noOfTranVar, String noOfSerVar) {
this.noOfTranVar = noOfTranVar;
this.noOfSerVar = noOfSerVar;
}
private void writeObject(ObjectOutputStream os) {
try {
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e) { e.printStackTrace(); }
}
private void readObject(ObjectInputStream is) {
try {
is.defaultReadObject();
int noOfTransients = (is.readInt());
} catch (Exception e) {
e.printStackTrace(); }
}
public int getNoOfTranVar() {
return noOfTranVar;
}
}
The value of transient variable ‘noOfTranVar’ is saved as part of the serialized object manually by implementing writeObject() and restored by implementing readObject().private static final long serialVersionUID =-22L;
private String noOfSerVar;
transient private int noOfTranVar;
TestCustomizedSerialization(int noOfTranVar, String noOfSerVar) {
this.noOfTranVar = noOfTranVar;
this.noOfSerVar = noOfSerVar;
}
private void writeObject(ObjectOutputStream os) {
try {
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e) { e.printStackTrace(); }
}
private void readObject(ObjectInputStream is) {
try {
is.defaultReadObject();
int noOfTransients = (is.readInt());
} catch (Exception e) {
e.printStackTrace(); }
}
public int getNoOfTranVar() {
return noOfTranVar;
}
}
The normal serializable variables are saved and restored by calling defaultWriteObject() and defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization process for the object to be saved or restored respectively.
No comments:
Post a Comment