作者NTUtzboy (台大资男哟)
看板java
标题Re: [心得] 序列化的小细节
时间Thu Oct 26 01:37:30 2006
问题出在这:(节录自J2SE1.4 API)
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.
所以"a.object"储存了两个物件, "b.object"也同样储存了两个物件
(不信的话可以直接把a.object档打开看, 一定看的懂的...)
因此读取的结果是, A有两个instances, B也有两个
其中某个A.b是指向一个B instance; 另一个A的refernce b则是指向另一个B instance
自己画画图就很清楚了...
不过也很感谢p大找出这个问题呢:)
※ 引述《PsMonkey (痞子军团团长)》之铭言:
: 请原谅我帮忙加个注解...
: (坦白说,我翻来翻去,看好久才知道确定差异在哪 XDXD)
: ※ 引述《pao0111 (Pao)》之铭言:
: : 分别写入两个档案:
: //这是会导致 reference 失败的写法
: //差异点在於,这边存在两个不同的档案当中
: : FileOutputStream fos = new FileOutputStream("a.object");
: : ObjectOutputStream oos = new ObjectOutputStream(fos);
: : oos.writeObject(a);
: : oos.close();
: : fos = new FileOutputStream("b.object");
: : oos = new ObjectOutputStream(fos);
: : oos.writeObject(b);
: : oos.close();
: : 嗯,没错误发生。
: : 可见互相参考甚至是循环参考对物件的序列化是没问题的。
: : 在别的程式里,读出那两个物件来:
: : FileInputStream fis = new FileInputStream("a.object");
: : ObjectInputStream ois = new ObjectInputStream(fis);
: : A a = (A)ois.readObject();
: : fis = new FileInputStream("b.object");
: : ois = new ObjectInputStream(fis);
: : B b = (B)ois.readObject();
: : 此时:
: : System.out.println(a.b == b);
: : System.out.println(a.b.a == a);
: : System.out.println(b.a == a);
: : System.out.println(b.a.b == b);
: : 印出来的是:
: : false
: : true
: : false
: : true
: : 哎呀!参照居然变了!
: 我比较想知道,这时候的 a.b 会指到哪里去 @__@???
: 为甚麽 a.b.a 又会指回来自己 @__@???
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.139.216.85
※ 编辑: NTUtzboy 来自: 220.139.216.85 (10/26 01:38)