Is a deserialised object the same instance as the original

前端 未结 5 1881
心在旅途
心在旅途 2021-02-04 02:07

When I instantiate an object from a class, an object is saved in the java heap. When I save the object by serializing it and I later deserialize the object, do I understand corr

5条回答
  •  我在风中等你
    2021-02-04 02:28

    Before serializing:

    A originalA = ...;
    B.a == C.a == D.a == E.a == originalA
    

    All B.a, C.a, D.a and E.a point to the same reference of A, originalA.

    After serializing and deserializing:

    A otherA = ...;
    B.a == C.a == D.a == E.a == otherA
    

    All B.a, C.a, D.a and E.a point to the same reference of A, otherA.

    However:

    originalA != otherA
    

    though

    originalA.equals(otherA) == true
    

    Note: equals() will return true only if it is overriden to consistently check equality based on serialized fields. Otherwise, it might return false.


    EDIT:

    Proof:

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    public class Sample {
    
        static class A implements Serializable {
            private static final long serialVersionUID = 1L;
        }
    
        static class B implements Serializable {
            private static final long serialVersionUID = 1L;
    
            A a;
        }
    
        static class C implements Serializable {
            private static final long serialVersionUID = 1L;
    
            A a;
        }
    
        public static void main(String args[]) throws IOException, ClassNotFoundException {
            A originalA = new A();
    
            B b = new B();
            b.a = originalA;
    
            C c = new C();
            c.a = originalA;
    
            System.out.println("b.a == c.a is " + (b.a == c.a));
    
            FileOutputStream fout = new FileOutputStream("ser");
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(b);
            oos.writeObject(c);
            oos.close();
            fout.close();
    
            FileInputStream fileIn = new FileInputStream("ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            B bDeserialized = (B) in.readObject();
            C cDeserialized = (C) in.readObject();
            in.close();
            fileIn.close();
    
            System.out.println("bDeserialized.a == cDeserialized.a is " + (bDeserialized.a == cDeserialized.a));
        }
    }
    

提交回复
热议问题