Wednesday, July 22, 2015

Serialization with Externalizable


  • Class implements Externalizable. Class has to implement writeExternal() and readExternal().
  • We have to define our own implementation for serialization and deserialization process. Default implementation is not available(Unlike Serializable).
  • During deserialization default constructor is used. Hence default constructor is must. Otherwise BOOOM.
  • Serialization using Externalizable is little faster than Serializable.
  • Super.writeExternal() needs to be executed for super class field’s serialization.
Example:- 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Student implements Externalizable {
 
 private String name;
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public void writeExternal(ObjectOutput out) throws IOException {
  out.writeObject(name);
 }

 @Override
 public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
  name = (String) in.readObject();
 }
}


public class Serialize {
 
 public static void main(String[] args) throws FileNotFoundException, IOException {
  Student student = new Student();
  student.setName("External");
  ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student_ex.ser"));
  out.writeObject(student);
  out.close();
  System.out.println("Serialization complete");
 }
}


public class Deserialize {
 public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
  ObjectInputStream in = new ObjectInputStream(new FileInputStream("student_ex.ser"));
  Student student = (Student) in.readObject();
  in.close();
  System.out.println(student.getName());
 }
}

No comments:

Post a Comment