|
|
Re: Write Object Anomaly
|
Posted: Nov 23, 2004 6:40 PM
|
|
If you write the same object twice then Jav serialization just keeps the reference of the first one and marks the second write to the old reference. So, it doesn't write the second object fresh. Please see the Jav documentation mentioned below. This is done to reduce the amount of data being serailized. If you want your object to be written twice then there are two ways: 1. After writing first time or before writing second time, call o1.reset(). After call to reset(), Java doesn't refer back for old object references. 2. Clone first one and write it second time.
******************************************************* Here is Java documentation on Class ObjectOutputStream: "The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. "
Here is reset method decription: reset public void reset() throws IOExceptionReset will disregard the state of any objects already written to the stream. The state is reset to be the same as a new ObjectOutputStream. The current point in the stream is marked as reset so the corresponding ObjectInputStream will be reset at the same point. Objects previously written to the stream will not be refered to as already being in the stream. They will be written to the stream again.
import java.io.*;
class Animal implements Serializable {
private String name;
Animal(String n) { name = n; }
public void chgName(String s) { name = s; }
public String toString() { return ("[" + name + "]"); }
}
public class WriteObjectAnomaly {
public static void main(String[] args) throws Exception {
Animal myPet = new Animal("Bosco");
ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
ObjectOutputStream o1 = new ObjectOutputStream(buf1);
o1.writeObject(myPet);
o1.flush();
o1.reset(); // Got to do this
myPet.chgName("Lassie");
o1.writeObject(myPet);
ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
ObjectOutputStream o2 = new ObjectOutputStream(buf2);
o2.writeObject(myPet);
ObjectInputStream in1 = new ObjectInputStream(
new ByteArrayInputStream(buf1.toByteArray()));
ObjectInputStream in2 = new ObjectInputStream(
new ByteArrayInputStream(buf2.toByteArray()));
Animal out1Write1 = (Animal)in1.readObject();
Animal out1Write2 = (Animal)in1.readObject();
Animal out2Write1 = (Animal)in2.readObject();
System.out.println("out1Write1: " + out1Write1);
System.out.println("out1Write2: " + out1Write2);
System.out.println("out2Write1: " + out2Write1);
}
}
|
|