码迷,mamicode.com
首页 > 其他好文 > 详细

自定义序列化

时间:2015-09-07 12:55:18      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

package File;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.IOException;
public class SerializeTest {
	public static void main(String[] args) {
		try (ObjectOutputStream oos = new ObjectOutputStream(
				new FileOutputStream("transient.txt"));
				ObjectInputStream ois = new ObjectInputStream(
						new FileInputStream("transient.txt"))) {
			Person per = new Person("孙悟空", 500);
			oos.writeObject(per);
			Person p = (Person) ois.readObject();
			System.out.println(p.getName());//输出空悟孙
			System.out.println(p.getAge());//输出501
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
class Person implements Serializable {           //序列化的类必须实现Serializable或Externalizable接口
	private String name;
	private transient int age;//transient表示不进行不序列化

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return this.name;
	}

	public int getAge() {
		return this.age;
	}

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

	public void setAge(int age) {
		this.age = age;
	}
	
	/*进行自定义序列化,要在序列化的类中添加两个方法,都是private,这里用到了反射*/
	
	private void writeObject(ObjectOutputStream out)throws IOException
	{
		out.writeObject(new StringBuffer(name).reverse());
		out.writeInt(age);
	}
	private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException
	{
		this.name = ((StringBuffer)in.readObject()).toString();
		this.age = in.readInt()+1;
	}
}

 

自定义序列化

标签:

原文地址:http://www.cnblogs.com/masterlibin/p/4788510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!