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對象.