Does Java Serialization work for cyclic references?

只谈情不闲聊 提交于 2019-12-18 14:30:31

问题


For example: Object A contains Object B that contains Object C that contains Object A.

Will Object A serialize properly?

Comment #9 here indicates that it does not work .

In contrast, XStream indicates that it does handle cyclic references.


回答1:


Yes, the default Java serialization works for cyclic references. When you serialize object C, the field will contain a backreference to the already-serialized object A instead of serializing it again.




回答2:


Yes, Java serialization works for circular references, read here for more information to help your understanding of what Java serialization can do.




回答3:


Yes it does.

I did this very, very, simple test, and at least it finish the serialization. I assume it is correct, but you can check that with some extra lines.

import java.io.*;
class A implements Serializable { B b; }
class B implements Serializable { C c; }
class C implements Serializable { A a; }
class Test {
    public static void main( String [] args ) throws IOException {
        A a = new A();
        a.b = new B();
        a.b.c = new C();
        a.b.c.a = a;
        new ObjectOutputStream( new ByteArrayOutputStream( ) ).writeObject( a );
        System.out.println("It works");

    }    
}



回答4:


You can actually view the referencing firsthand if you serialize your object to XML. The child objects are only serialized once. Any reference (anywhere in the serialized structure) to a child object that has already been serialized will simply point to that object in the file.

Serializing cyclic references can get a little messy, though, so you might want to avoid them if you can.



来源:https://stackoverflow.com/questions/1792501/does-java-serialization-work-for-cyclic-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!