序列化和反序列化(八)——Externalizable接口

       Externalizable接口:该接口继承自 Serializable接口,Externalizable接口定义了两个抽象方法:writeExternal()readExternal(),通过这些方法指定序列化哪些属性不序列化哪些属性。注意:实现Externalizable接口的类可以不设置serialVersionUID常量,但必须要求序列化前后的两个类完全相同,为了编程更显灵活,推荐设置serialVersionUID常量。

       示例:

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class UserInfo implements Externalizable {

	private int age;
	private String name;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeObject(name);
		out.writeInt(age);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		name = (String) in.readObject();
		age = in.readInt();
	}

	@Override
	public String toString() {
		return "name='" + name + '\'' + ", age=" + age;
	}
}
import java.io.*;

public class Test {
	
	/**
	 * 序列化
	 * 
	 * @author GaoHuanjie
	 */
	public static void serialize(){
		UserInfo userInfo = new UserInfo();
		userInfo.setAge(23);
		userInfo.setName("Tom");
		System.out.println(userInfo);
		ObjectOutput objectOutput = null;
		try {
			objectOutput = new ObjectOutputStream(new FileOutputStream("D:\\user_info.ser"));
			objectOutput.writeObject(userInfo);
			objectOutput.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (objectOutput!=null) {
				try {
					objectOutput.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 反序列化
	 * 
	 * @author GaoHuanjie
	 */
	public static void deserialize(){
		ObjectInput objectInput = null;
		try {
			objectInput = new ObjectInputStream(new FileInputStream("D:\\user_info.ser"));
			UserInfo userInfo = (UserInfo) objectInput.readObject();
			System.out.println(userInfo);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (objectInput!=null) {
				try {
					objectInput.close();
				} catch (IOException e) {
					e.printStackTrace();
				} 
			}
		}
	}

	public static void main(String[] args) {
		serialize();//序列化
		deserialize();//反序列化
	}
}

       Serializable接口与Externalizable接口区别:

              1、Serializable反序列化时不会调用默认构造方法,而Externalizable反序列化时会调用默认构造器方法;

              2、Serializable反序列化时构造方法可以是任意访问权限的控制符,而Externalizable反序列化时只能是public

              3、Serializable序列化时,statictransient修饰的属性不会被序列化,而Externalizable序列化时只能通过writeExternal()readExternal()方法指定序列化哪些属性不序列化哪些属性,不能使用transient修饰符;

你可能感兴趣的:(序列化与反序列化)