Xiè*_*léi 8 java serialization
我无法控制基类的源代码,那么,如何在子类上使用标准序列化?
在此示例中,字段a根本没有序列化,但B是可序列化的:
// a.jar
class A {
int a;
}
Run Code Online (Sandbox Code Playgroud)
// 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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
0
20
Run Code Online (Sandbox Code Playgroud)
你不能!
字段a不会被序列化!
解决方法:实现自定义序列化.您应该实现Externalizable接口和writeExternal, readExternal方法.在thess方法中,您可以编写和读取a字段的值.
| 归档时间: |
|
| 查看次数: |
1605 次 |
| 最近记录: |