亲宝软件园·资讯

展开

Java序列化和反序列化

攻城狮Chova 人气:0

基本概念

序列化

public class Person implements Serializable {
	private String name;
	private int age;

	public Person() {
		System.out.println("无参构造...");
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
		System.out.println("有参构造...");
	}

	@Override
	public String toString() {
		return "Person{" +
				"name='" + name + "\'" +
				", age='" + age + "\'"
				"}";
	}
}
public class SerializableTest {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		Person person = new Person("Lily", 20);

		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.txt"));
		oos.writeObject(person);
		oos.close();
	}
}

反序列化

public class  DeserializableTest {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Person.txt"));
		Pesron person = (Person)ois.readObject(ois);
		System.out.println(person);
	}
}

序列化和反序列化总结

自定义序列化策略

Externalizable

public class CustomExternal implements Externalizable {
	
	private String name;
	
	private int code;

	public CustomExternal() {
		System.out.println("无参构造...");
	}
	
	public CustomExternal(String name, int code) {
		this.name = name;
		this.code = code;
		System.out.println("有参构造...");
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		System.out.println("执行writeExternal()方法...");
		out.writeObject(name);
		out.writeInt(code);
	} 

	@Override
	public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
		System.out.println("执行readExternal()方法...");
		name = (String) in.readObject();
		code = in.readInt();
	}

	@Override
	public String toString() {
		return "类:" + name + code;
	}

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		CustomExternal custom = new CustomeExternal("oxford", 666);
		System.out.println(custom);
		
		// 序列化
		ObjectOutputStream out = new ObjectOutputStream(new FileInputStream("oxford.txt"));
		System.out.println("序列化对象...");
		out.writeObject(custom);
		out.close();

		// 反序列化
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("oxford.txt"));
		System.out.println("反序列化对象...");
		custom = (CustomExternal) in.readObject();
		System.out.println(custom);
		in.close();
	}
}

有参构造...
类:oxford666
序列化对象...
执行writeExternal()方法...
反序列化对象...
无参构造...
执行readExternal()方法...
类:oxford666 

transient

静态变量

序列化ID

破坏单例

总结

加载全部内容

相关教程
猜你喜欢
用户评论