Java语言中对象的部分序列化

public class TestExternalizable implements Externalizable {

	//只对下面2个变量序列化
	int No;
	String name;
	
	//下面的变量没有被序列化
	int age = 0;

	public TestExternalizable() {
		// 在恢复Externalizable对象的时候,默认构造函数会被调用,这一点跟恢复一个Serializable对象不同
		System.out.println("Default Constructor");
	}

	public TestExternalizable(int No, String name, int age) {

		System.out.println("Other Constructor");
		this.name = name;
		this.No = No;
		this.age = age;
	}

	@Override
	public String toString() {
		return "No: " + No + ", Name: " + name + ", age: " + age;
	}

	//序列化数据时调用的函数
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeInt(No);
		out.writeObject(name);
	}

	//恢复数据时调用的函数。需要保证恢复的数据跟序列化时一致
	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {

		No = in.readInt();
		name = (String) in.readObject();
	}

	public static void main(String[] args) {

		TestExternalizable te = new TestExternalizable(10, "lnmcc", 18);
		System.out.println(te.toString());

		try {
			//将一个Externalizable对象保存到一个文件
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("out.dat"));
			out.writeObject(te);
			//刷新并关闭流
			out.close();

			//从文件恢复一个Externalizable对象
			ObjectInputStream in = new ObjectInputStream(new FileInputStream("out.dat"));
			te = (TestExternalizable) in.readObject();
			System.out.println(te.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

输出:

Other Constructor
No: 10, Name: lnmcc, age: 18
Default Constructor
No: 10, Name: lnmcc, age: 0

结果显示:

  1. 反序列化一个Externalizable对象的时候会调用类的默认构造函数。
  2. No和Name字段成功恢复,age字段由于没有被序列化,为默认值。