【发布时间】:2021-08-23 14:50:09
【问题描述】:
我正在阅读 Java 中的 custom serialization,您在要序列化的类中提供以下两种方法:
private void writeObject(ObjectOutputStream oos)
private void readObject(ObjectInputStream ois)
例如:
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private transient Address address;
private Person person;
// setters and getters
private void writeObject(ObjectOutputStream oos)
throws IOException {
oos.defaultWriteObject();
oos.writeObject(address.getHouseNumber());
}
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
ois.defaultReadObject();
Integer houseNumber = (Integer) ois.readObject();
Address a = new Address();
a.setHouseNumber(houseNumber);
this.setAddress(a);
}
}
当你想反序列化Employee类的序列化对象时如下:
Employee e2 = (Employee) objectInputStream.readObject();
Java 虚拟机将调用类Employee 中定义的readObject(ObjectInputStream ois) 方法,而不是ObjectInputStream 类(source) 的readObject()。但是,前一种方法不返回任何内容 (void),这与后一种方法返回 Object 类型(应该强制转换)不同。
那么,我们还怎么从上面的自定义反序列化过程中得到Employee对象呢?
【问题讨论】:
-
我想我以前做过这个,iirc 我将
ObjectOutputStream转换为DataOutputStream,然后将各个字段写入流。然后在阅读时,我只需使用DataInputStream并阅读并填写每个字段。瞧。
标签: java serialization deserialization