Does Java Serialization work for cyclic references?

前端 未结 4 1095
误落风尘
误落风尘 2021-01-01 18:16

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 d

4条回答
  •  鱼传尺愫
    2021-01-01 18:46

    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");
    
        }    
    }
    

提交回复
热议问题