Customized serialization in java

Customized serialization in java

Whenever We serialize the java objects There may chance of loss of data due to transient keyword. We can recover This lost data by using Customized serialization. we can implement Customized serialization by using following methods

  1. private void writeObject(ObjectOutputStream out) throws IOException;
  2. private void readObject(ObjectInputStream ins) throws IOException, ClassNotFoundException;

private void writeObject(ObjectOutputStream out) throws IOException:

This method will executed automatically at the time of serialization.

private void readObject(ObjectInputStream ins) throws IOException, ClassNotFoundException:

This method will execute automatically at the time of deserialzation

Customized Serialization Example:


package com.java2study;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Account implements Serializable{

private static final long serialVersionUID = 1L;
private String userName;
private String password;

public Account(String userName, String password) {

this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private void writeObject(ObjectOutputStream out) throws IOException {

out.defaultWriteObject();
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
public class Test {


public static void main(String[] args)throws Exception {

Account a = new Account("AAA","BBB");


FileOutputStream fos = new FileOutputStream("acc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a);


FileInputStream fis = new FileInputStream("acc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println("username is "+a2.getUserName() + "password is "+a2.getPassword());
}

}




output

 
username is AAApassword is BBB

-->