Which classes must implement the Serializable interface?

血红的双手。 提交于 2020-01-05 04:04:24

问题


I want to send an object via socket, so I have to implement Serializable. But my class is a compound class, like this simple code:

class B{
    private int a;
    public B(int aa){a=aa;}
}

class A {
    private B b;
    public A(B b1){ b=b1;}
}

I want to send an object of class A, with all it's contents such as the B object inside. Which classes should implement Serializable? just A, or both A and B?


Addition: How about vectors? Think that I have a Vector of B in A like this:

class A {
    private Vector bvector;
}

回答1:


You can serialize instances of A ,even if B is not declared as Serializable. The requirements for this is that

  1. Class B must make available a default constructor ( and)
  2. Class A must provide implementations of following methods :

    private void readObject(ObjectInputStream ois)

    private void writeObject(ObjectOutputStream oos)

It is definitely easier to serialize instances of A if class B is declared as Serializable Vs when it is not. The default serialization could be made to work if it does.

Having a Vector of B makes no difference in the above situation ( it just adds another layer of structure ).




回答2:


Both. A can't be serializable as long as it has a non-static member of type B and 1) variable b is not marked transient or 2) class B does not implement Serializable.




回答3:


If neither class is an inner class you can do it either way. Simpler in many cases to serialize both independently. But it's generally faster and more version-independent to serialize A and, instead of B, include the info needed to recreate B in A's serialization.

If one or both are inner classes then it gets messier/slower to serialize them, and better to include their recreation info in the outer class.

Of course, when objects of a class are referenced from multiple other objects, you usually have no choice but to serialize them separately.




回答4:


If you won't make B serializable you will get Serialization exception.




回答5:


You can have a wrapping class serialise Vector provided it is a field of another Serializable class, or sub class Vector to change its serializaton. This class can lock the Vector for Serialization and serialise A and B classes. If you use this approach, you don't need to add a Serializable marker interface.



来源:https://stackoverflow.com/questions/7050381/which-classes-must-implement-the-serializable-interface

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