maven 依赖
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.7</version>
</dependency>
工具类代码
package com.xxx.common.util;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
*
* @author zhuyl
* @ClassName: HessianUtil
* @Description: Hessian 序列化反序列化
* @Date 2016年03月15日 10:45
*/
public class HessianUtil {
/**
* 序列化
* @param obj
* @return
* @throws IOException
*/
public static byte[] serialize(Object obj) throws IOException {
if (obj == null) throw new NullPointerException("序列化对象为空");
ByteArrayOutputStream os=null;
HessianOutput ho = null;
try {
os = new ByteArrayOutputStream();
ho = new HessianOutput(os);
ho.writeObject(obj);
return os.toByteArray();
} finally {
close(os,ho,obj,null,null,null);
}
}
/**
* 反序列化
* @param by
* @return
* @throws IOException
*/
public static Object deserialize(byte[] by) throws IOException {
if (by == null) throw new NullPointerException("反序列化参数为空");
ByteArrayInputStream is=null;
HessianInput hi = null;
try {
is = new ByteArrayInputStream(by);
hi = new HessianInput(is);
return hi.readObject();
}
finally {
close(null,null,null,is,hi,by);
}
}
/**
* 释放资源
* @param os
* @param ho
* @param obj
* @param is
* @param hi
* @param by
*/
private static void close(ByteArrayOutputStream os,HessianOutput ho,Object obj,ByteArrayInputStream is,HessianInput hi,byte[] by){
try {
if(os!=null){
os.close();
os=null;
}
if(ho!=null){
ho.flush();
ho.close();
ho=null;
}
if(obj!=null){
obj=null;
}
if (is != null) {
is.close();
is=null;
}
if (hi != null) {
hi.close();
hi=null;
}
if (by != null) {
by=null;
}
} catch (Exception e) {
throw new RuntimeException("close IOException"+e);
}
}
}
demo代码
@Test
public void serializeTest() {
String msg = "demo test";
try {
//序列化
byte[] bb = HessianUtil.serialize(msg);
//反序列化
Object obj = HessianUtil.deserialize(bb);
} catch (IOException e) {
throw new RuntimeException("deserialize IOException", e);
}
}
注意点
1、被序列化类要实现Serializable接口,否则会报错
2、如果是在osgi环境中运行,比如karaf容器中用hession进行序列化和反序列化,那么hessian-4.0.7.jar 的MANIFEST.MF文件要另起一行,添加动态导入: “DynamicImport-Package: *”,否则反序列化后得到的对象会是HashMap,可能不是你想要的