【1】Object >> byte[].
约束:该对象必须可序列化,且其包含的各属性对象,也必须可序列化
注意:注释掉的部分为hessian实现方式
public static byte[] objectToBytes(Object obj){
byte[] result = null;
ByteArrayOutputStream byteOutputStream = null;
ObjectOutputStream objectOutputStream = null;
// Hessian2Output objectOutputStream2 = null;
try{
byteOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
// objectOutputStream2.startMessage();
// objectOutputStream2.writeObject(obj);
// objectOutputStream2.completeMessage();
result = byteOutputStream.toByteArray();
}catch(Exception e){
e.printStackTrace();
} finally {
if(null != objectOutputStream){
try{
objectOutputStream.close();
byteOutputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return result;
}
【2】byte[] >> Object
约束:如果byte[]里的类型与所转类型不同,则会抛异常java.lang.ClassCastException
注意:注释掉的部分为hessian实现方式
public static Object bytesToObject(byte[] bytes){
Object result = null;
ByteArrayInputStream byteInputStream = null;
ObjectInputStream objectInputStream = null;
// Hessian2Input objectInputStream2 = null;
try{
byteInputStream = new ByteArrayInputStream(bytes);
objectInputStream = new ObjectInputStream(byteInputStream);
result = objectInputStream.readObject();
// objectInputStream2.startMessage();
// result = objectInputStream2.readObject();
// objectInputStream2.completeMessage();
}catch(Exception e){
e.printStackTrace();
}finally {
if(null != objectInputStream){
try{
objectInputStream.close();
byteInputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return result;
}