Sometimes (quite a lot, actually) we get a situation in Java where two objects are pointing to the same thing. Now if we serialise these separately it is quite appropriate that the serialised forms have separate copies of the object as it should be possible to open one without the other. However if we now deserialise them both, we find that they are still separated. Is there any way to link them back together?
Example follows.
public class Example {
private static class ContainerClass implements java.io.Serializable {
private ReferencedClass obj;
public ReferencedClass get() {
return obj;
}
public void set(ReferencedClass obj) {
this.obj = obj;
}
}
private static class ReferencedClass implements java.io.Serializable {
private int i = 0;
public int get() {
return i;
}
public void set(int i) {
this.i = i;
}
}
public static void main(String[] args) throws Exception {
//Initialise the classes
ContainerClass test1 = new ContainerClass();
ContainerClass test2 = new ContainerClass();
ReferencedClass ref = new ReferencedClass();
//Make both container class point to the same reference
test1.set(ref);
test2.set(ref);
//This does what we expect: setting the integer in one (way of accessing the) referenced class sets it in the other one
test1.get().set(1234);
System.out.println(Integer.toString(test2.get().get()));
//Now serialise the container classes
java.io.ObjectOutputStream os = new java.io.ObjectOutputStream(new java.io.FileOutputStream("C:\\Users\\Public\\test1.ser"));
os.writeObject(test1);
os.close();
os = new java.io.ObjectOutputStream(new java.io.FileOutputStream("C:\\Users\\Public\\test2.ser"));
os.writeObject(test2);
os.close();
//And deserialise them
java.io.ObjectInputStream is = new java.io.ObjectInputStream(new java.io.FileInputStream("C:\\Users\\Public\\test1.ser"));
ContainerClass test3 = (ContainerClass)is.readObject();
is.close();
is = new java.io.ObjectInputStream(new java.io.FileInputStream("C:\\Users\\Public\\test2.ser"));
ContainerClass test4 = (ContainerClass)is.readObject();
is.close();
//We expect the same thing as before, and would expect a result of 4321, but this doesn't happen as the referenced objects are now separate instances
test3.get().set(4321);
System.out.println(Integer.toString(test4.get().get()));
}
}