Java Reference
In-Depth Information
Writing an Object More Than Once to a Stream
The JVM keeps track of object references it writes to the object output stream using the
writeObject()
method.
Suppose you have a
PersonMutable
object named
john
and you use an
ObjectOutputStream
object
oos
to write it to a
file as follows:
PersonMutable john = new PersonMutable("John", "Male", 6.7);
oos.writeObject(john);
At this time, Java makes a note that the object
john
has been written to the stream. You may want to change some
attributes of the
john
and write it to the stream again as follows:
john.setName("John Jacobs");
john.setHeight(5.9);
oos.writeObject(john);
At this time, Java does not write the
john
object to the stream. Rather, the JVM back references it to the
john
object that you wrote the first time. That is, all changes made to the
name
and
height
fields are not written to the
stream separately. Both writes for the
john
object share the same object in the written stream. When you read the
objects back, both objects will have the same
name
,
gender
, and
height
.
An object is not written more than once to a stream to keep the size of the serialized objects smaller. Listing 7-29
shows this process. The
MultipleSerialization
class as shown in Listing 7-30, in its
serialize()
method, writes an
object, changes object's attributes, and serializes the same object again. It reads the objects in its
deserialize()
method.
The output shows that Java did not write the changes made to the object when it wrote the object the second time.
Listing 7-29.
A MutablePerson Class Whose Name and Height Can Be Changed
// MutablePerson.java
package com.jdojo.io;
import java.io.Serializable;
public class MutablePerson implements Serializable {
private String name = "Unknown";
private String gender = "Unknown" ;
private double height = Double.NaN;
public MutablePerson(String name, String gender, double height) {
this.name = name;
this.gender = gender;
this.height = height;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}