Object Streams and Serialization
Home ] Up ] [ Object Streams and Serialization ] Serializing Families of Classes ] Serialization and Class Versioning ] Custom Serialization and Security ] Serialized Applets ] Advanced Serialization ]

 

 

Here's the relevant class hierarchy for object streams:

(Package java.io)

Object
    InputStream
        ObjectInputStream
    OutputStream
        ObjectOutputStream
Serializable
    Externalizable
ObjectInputValidation

Classes ObjectOutputStream and ObjectInputStream

Serialization is achieved using the classes ObjectOutputStream and ObjectInputStream.

However, a class must implement the Serializable interface to be successfully serialized. (This is not the default for security reasons.) The Serializable interface is a 'marker interface' -- that is, it has no methods -- so no other changes need to be made to your classes.

To serialize your class out to an ObjectOutputStream, you call that stream's writeObject() method. Conversely, when you wish to serialize in from an ObjectInputStream, you call that stream's readObject() method.

Here is how you can serialize out to a file. First, let's create some classes to serialize:

package serialization;

import java.io.Serializable;

public class Person
    implements Serializable
{
    public Person(String name, int age)
    {
        m_name = name;
        m_age  = age;
    }
    
    public String getName()
    {
        return m_name;
    }
    
    public int getAge()
    {
        return m_age;
    }
    
    public String toString()
    {
        String s = getClass().getName();
        s += ":Name=" + m_name + ", Age=" + m_age;
        return s;
    }
    
    /////// Data ////////
    private String  m_name;
    private int     m_age;
}
package serialization;

public class Employee
    extends Person
{
    public Employee(String name,   int  age, 
                    double salary, long id)
    {
        super(name, age);
        m_salary = salary;
        m_id = id;
    }
    
    public double getSalary()
    {
        return m_salary;
    }
    
    public long getId()
    {
        return m_id;
    }
    
    public String toString()
    {
        String s = super.toString();
        s += ", Salary=" + m_salary + ", ID=" + m_id;
        return s;
    }
    
    
    /////// Data ///////
    private double m_salary;
    private long   m_id;
}
package serialization;

import java.util.Vector;

public class Manager
    extends Employee
{
    public Manager(String name,   int  age,
                   double salary, long id)
    {
        super(name, age, salary, id);
    }
    
    public void addEmployee(Employee emp)
    {
        m_directReports.addElement(emp);
    }

    public void removeEmployee(Employee emp)
    {
        m_directReports.removeElement(emp);
    }
    
    ///// Data ////
    private Vector m_directReports = new Vector();
}

Here's how you serialize objects of these types out to a file:

package serialization;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SimpleSerializeOut
{
    public static void main(String[] args)
    {
        Manager bill = new Manager("Bill Gates", 47,
                                   100000000000.00, 1);
        Employee bob = new Employee("Bob Dole", 69,
                                    100000.00, 345);
        ObjectOutputStream out = null;
        try
        {
            out = new ObjectOutputStream(
                          new FileOutputStream(
                                   "employees.dat"));
            out.writeObject(bob);
            out.writeObject(bill);
            System.out.println("Serialization successful.");
        }
        catch(IOException e)
        {
            e.printStackTrace();
            System.out.println("Serialization failed.");
        }
        finally
        {
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch(IOException e)
                {}
            }
        }
    }
}

And here's how you serialize them back in again, from the file:

package serialization;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class SimpleSerializeIn
{
    public static void main(String[] args)
    {
        Employee emp;
        Manager  mgr;
        
        ObjectInputStream in = null;
        boolean failed = true;
        try
        {
            in = new ObjectInputStream(
                          new FileInputStream(
                                   "employees.dat"));
            emp = (Employee)in.readObject();
            System.out.println("emp: " + emp);
            mgr = (Manager)in.readObject();
            System.out.println("mgr: " + mgr);
            System.out.println("Serialization successful.");
            failed = false;
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch(IOException e)
                {}
            }
            if (failed)
                System.err.println("Serialization failed.");
        }
    }
}

This latter program outputs the following:

emp: serialization.Employee:Name=Bob Dole, Age=69, Salary=100000.0, ID=345
mgr: serialization.Manager:Name=Bill Gates, Age=47, Salary=1.0E11, ID=1
Serialization successful.

which shows that it worked!

 
The page was last updated February 19, 2008