基于Hession完成对象的序列化和反序列化

Step01:定义mail类:

public class Mail implements Serializable{
	private static final long serialVersionUID = 6599166688654530165L;
	private Integer id;
	private String title;
	private String content;
	private Date createdTime;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getCreatedTime() {
		return createdTime;
	}
	public void setCreatedTime(Date createdTime) {
		this.createdTime = createdTime;
	}
	@Override
	public String toString() {
		return "Mail [id=" + id + ", title=" + title + ", content=" + content + ", createdTime=" + createdTime + "]";
	}
}

Step02:添加依赖

<dependency>
	<groupId>com.caucho</groupId>
	<artifactId>hessian</artifactId>
	<version>4.0.60</version>
</dependency>

Step03: 编写测试类,基于文档说明,实现序列化和反序列化,可参考官方:

http://hessian.caucho.com/doc/hessian-overview.xtp

在测试类中添加序列化和反序列化方法,完成序列化和反序列化操作.创建测试类TestSerializable03,然后添加对象序列化方法定义

private static void doSerialization(Object obj) throws FileNotFoundException, IOException {
		OutputStream os = new FileOutputStream("test.xml");
		Hessian2Output out = new Hessian2Output(os);
		out.writeObject(obj);
		out.flush();
		os.close();
}

添加对象反序列化方法定义

private static Object doDeserialization() throws FileNotFoundException, IOException {
		InputStream is = new FileInputStream("test.xml");
		Hessian2Input in = new Hessian2Input(is);
		Object obj2 = in.readObject();
		is.close();
		return obj2;
}

添加main方法进行测试:

public static void main(String[] args)throws Exception {
		Mail obj = new Mail();
		obj.setId(200);
		obj.setTitle("test");
		obj.setContent("this is test content");
		obj.setCreatedTime(new Date());
		//序列化
	        doSerialization(obj);
		//反序列化
		Mail obj2 =(Mail)doDeserialization();
		System.out.println(obj2);
	}

说明:可将如上序列化方法进行封装,写到序列化工具类中,例如

public class SerializationUtil {
	//反序列化
	@SuppressWarnings("unchecked")
	public static <T>T doDeserialization(String file) throws FileNotFoundException, IOException {
		InputStream is = new FileInputStream(file);
		Hessian2Input in = new Hessian2Input(is);
		T t =(T)in.readObject();
		is.close();
		return t;
	}
	//序列化
	public static <T extends Serializable>void 
	     doSerialization(T obj,String file) throws FileNotFoundException, IOException {
		OutputStream os = new FileOutputStream(file);
		Hessian2Output out = new Hessian2Output(os);
		out.writeObject(obj);
		out.flush();
		os.close();
	}
}

基于Hessian实现java对象序列化,java类仍需实现Serializable对象.

 

猜你喜欢

转载自blog.csdn.net/qianzhitu/article/details/103009083
今日推荐