以下是示例。
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()));
}
}