Friday 26 August 2016

Is serializable class require default constructor while doing serialization and deserialization?

No, it is not required. A serializable class needs not to provide default (no argument) constructor to perform serialization and deserialization.


Employee.java
import java.io.Serializable;

public class Employee implements Serializable {
 private static final long serialVersionUID = 1234L;

 private int id;
 private String firstName, lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

 public Employee(int id, String firstName, String lastName) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

}

As you see above snippet, Employee class don’t have any default constructor. Test.java class performs serialization and deserialization of Employee object.


Test.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {
 private static ObjectOutputStream out;
 private static ObjectInputStream in;

 public static void main(String args[]) throws IOException, ClassNotFoundException {
  /* Serialize object */
  FileOutputStream fos = new FileOutputStream("ser.out");
  out = new ObjectOutputStream(fos);
  Employee emp = new Employee(1, "Hari Krishna", "Gurram");
  out.writeObject(emp);

  /* Deserialize object */
  FileInputStream fis = new FileInputStream("ser.out");
  in = new ObjectInputStream(fis);
  Employee emp1 = (Employee) in.readObject();

  System.out.println(emp1);
 }
}


Output

Employee [id=1, firstName=Hari Krishna, lastName=Gurram]

How the deserialization happens?
JVM that allows an object to be created without invoking any constructor. The fields of the new object are first initialized to their default values (false, 0, null, etc), and then the object deserialization code populates the fields with values from the object stream.


You may like



No comments:

Post a Comment