# Externalizable 的替代方法
实现 Serializable 接口,并添加(注意是“添加”,而非“覆盖”或者“实现”)名为writeObject()和 readObject()的方 法
一旦对象被序列化或者重新装配,就会分别调用那两个方法
这些方法必须含有下列准确的签名:
private void
writeObject(ObjectOutputStream stream)
throws IOException;
private void
readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
大家可能奇怪 ObjectOutputStream 和ObjectInputStream 如何有权访问我们的类的 private方法——只能认为这是序列 化机制玩的一个把戏
看起来似乎我们调用ObjectOutputStream.writeObject()的时候,我们传递给它的Serializable 对象似乎会被检查是否实现 了自己的writeObject()。
若答案是肯定的是,便会跳过常规的序列化过程,并调用writeObject()。readObject()也会遇到同样的情况
实现 Serializable 接口,并添加(注意是“添加”,而非“覆盖”或者“实现”)名为writeObject()和 readObject()的方 法
一旦对象被序列化或者重新装配,就会分别调用那两个方法
这些方法必须含有下列准确的签名:
private void
writeObject(ObjectOutputStream stream)
throws IOException;
private void
readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
大家可能奇怪 ObjectOutputStream 和ObjectInputStream 如何有权访问我们的类的 private方法——只能认为这是序列 化机制玩的一个把戏
看起来似乎我们调用ObjectOutputStream.writeObject()的时候,我们传递给它的Serializable 对象似乎会被检查是否实现 了自己的writeObject()。
若答案是肯定的是,便会跳过常规的序列化过程,并调用writeObject()。readObject()也会遇到同样的情况
在我们的 writeObject() 内部,可以调用defaultWriteObject(),从而决定采取默认的writeObject()行动。类似地,在readObject()内部,可以调用defaultReadObject()
package com.zy.chapter10;
import java.io.*;
class People2 implements Serializable{
private void writeObject(ObjectOutputStream stream) throws IOException{
//use defaule writeObject
//stream.defaultWriteObject();
System.out.println("custom writeObject");
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException{
//use defaule writeObject
//stream.defaultReadObject();
System.out.println("custom readObject");
}
}
/**
*
* @ClassName SerializableImplDemo.java
* @function writeObject and readObject
* @author yiz
* @version V1.0
* @date 2018年1月11日
*/
public class SerializableImplDemo {
public static void main(String[] args) {
People2 p=new People2();
try {
ObjectOutputStream objouts=new ObjectOutputStream(new FileOutputStream("SerializableImplDemo.txt"));
objouts.writeObject(p);
objouts.close();
ObjectInputStream objins=new ObjectInputStream(new FileInputStream("SerializableImplDemo.txt"));
People2 p1=(People2)objins.readObject();
objins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
custom writeObject
custom readObject