我无法控制基类的源代码,那么,如何在子类上使用标准序列化呢?
在这个例子中,字段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