8

我无法控制基类的源代码,那么,如何在子类上使用标准序列化呢?

在这个例子中,字段a根本没有被序列化,尽管 B 是可序列化的:

// 一个.jar

class A {
    int a;
}

// b.jar

class B
        extends A
        implements Serializable {
    int b;
}

public class HelloWorldApp {

    public static void main(String[] args)
            throws Exception {
        B b = new B();
        b.a = 10;
        b.b = 20;

        ByteArrayOutputStream buf = new ByteArrayOutputStream();

        ObjectOutputStream out = new ObjectOutputStream(buf);
        out.writeObject(b);
        out.close();

        byte[] bytes = buf.toByteArray();
        ByteArrayInputStream _in = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(_in);
        B x = (B) in.readObject();
        System.out.println(x.a);
        System.out.println(x.b);
    }

}

输出:

0
20
4

1 回答 1

7

你不能!
字段a不会被序列化!
解决方法:实现您的自定义序列化。您应该实现Externalizable接口和writeExternal, readExternal方法。在这些方法中,您可以写入和读取a字段的值。

于 2012-05-08T06:27:25.133 回答