如何在标准序列化中序列化不可序列化的基类



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

在此示例中,字段 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

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

最新更新