Externalizable Interface in Java


Externalization is used whenever we need to customize serialization mechanism. If a class implements an Externalizable interface then, object serialization will be done using writeExternal() method. Whereas at receiver's end when an Externalizable object is a reconstructed instance will be created using no argument constructor and then the readExternal() method is called.

If a class implements only Serializable interface object serialization will be done using ObjectoutputStream. At the receiver's end, the serializable object is reconstructed using ObjectInputStream.

Below example showcases usage of Externalizable interface.

Example

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Tester {
   public static void main(String[] args) {

      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.age = 30;
      try (
         FileOutputStream fileOut = new FileOutputStream("test.txt");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
      ) {
         out.writeObject(e);
      }catch (IOException i) {
         System.out.println(i.getMessage());
      }
      try (
         FileInputStream fileIn = new FileInputStream("test.txt");
         ObjectInputStream in = new ObjectInputStream(fileIn);
      ) {
         e = (Employee)in.readObject();
         System.out.println(e.name);
         System.out.println(e.age);
      } catch (IOException i) {
         System.out.println(i.getMessage());
      } catch (ClassNotFoundException e1) {
         System.out.println(e1.getMessage());
      }
   }
}

class Employee implements Externalizable {
   public Employee(){}
   String name;
   int age;
   public void writeExternal(ObjectOutput out) throws IOException {
      out.writeObject(name);
      out.writeInt(age);
   }
   public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
      name = (String)in.readObject();
      age = in.readInt();
   }
}

This will produce the following result −

Output

Reyan Ali
30

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 21-Jun-2020

828 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements