如何在标准序列化中序列化非序列化基类? [英] How to serialize non-serializable base class in standard serialization?

查看:103
本文介绍了如何在标准序列化中序列化非序列化基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't control the source code of the base class, then, how can I use standard serialization on the subclass?

在本例中,字段 a 根本没有序列化,但B是可序列化的:

In this example, field a is not serialized at all, though B is serializable:

// a.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 方法。
在thess方法中,您可以写入和读取 a 字段的值。

You can't!
field a will not be serialized!
Work around: implement your custom serialization. You should implement Externalizable interface and writeExternal, readExternal methods. In thess methods you can write and read value of your a field.

这篇关于如何在标准序列化中序列化非序列化基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆