我无法控制基类的源代码,那么,如何在子类上使用标准序列化呢?
在这个例子中,字段 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
接口(interface)和 writeExternal、readExternal
方法。
在这些方法中,您可以写入和读取 a
字段的值。
关于java - 如何在标准序列化中序列化不可序列化的基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10493521/