开发者

Which classes must implement the Serializable interface?

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

cl开发者_如何学Goass 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;
}


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.


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.


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 ).


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜