SE450: Serialization: Dealing with references [10/32] Previous pageContentsNext page

Objects will usually contain references to other objects.

Serialization writes out all referenced objects (and any objects they reference).

Effectively, it writes out the whole graphs of objects.

All referenced classes must be serializable for this to work.

file:Main2.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package serialization;
import java.io.*;

public class Main2 {
  public static void main(String args[]) {
    try {
      Person person = new Person("Matt", 30);
      PersonEntry entry = new PersonEntry(person, 1);
      ObjectOutputStream os
      = new ObjectOutputStream (new FileOutputStream("out.dat"));
      os.writeObject(entry);
      os.close();

      ObjectInputStream is
      = new ObjectInputStream (new FileInputStream("out.dat"));
      Object o = is.readObject();
      is.close();

      PersonEntry entry2 = (PersonEntry) o;
      System.out.println("Entry restored from file is" + entry2.toString());
    } catch (Exception e) { e.printStackTrace(); }
  }
}

class PersonEntry implements Serializable {
  private static final long serialVersionUID = 2008L;
  private Person person = null;
  private int personNumber = 0;

  public PersonEntry(Person person, int personNumber) {
    this.person = person;
    this.personNumber = personNumber;
  }
  public Person getPerson() {
    return person;
  }
  public int getPersonNumber() {
    return personNumber;
  }
  public String toString() {
    return person.toString() +  " Number " + Integer.toString(personNumber);
  }
}

@SuppressWarnings("serial")
class Person implements Serializable {
  private String name = "";
  private int age = 0;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  public String getName() {
    return name;
  }
  public int getAge() {
    return age;
  }
  public String toString() {
    return "Name: " + name + " Age: " + Integer.toString(age);
  }
}

Previous pageContentsNext page