hessian学习基础篇——序列化和反序列化
1、概念介绍把Java对象转换为字节序列的过程称为对象的序列化。
把字节序列恢复为Java对象的过程称为对象的反序列化。
对象的序列化主要有两种用途:
1) 数据介质存储
2) 数据网络传输
2、对象序列化实例
为了更好的理解hessian的序列化机制,所以把java和hessian的对象序列化实例都一一列出。
1)对象序列化--java
public byte[] serialize(Object obj) throws Exception {if(obj==null) throw new NullPointerException();ByteArrayOutputStream os = new ByteArrayOutputStream();ObjectOutputStream out = new ObjectOutputStream(os);out.writeObject(obj);return os.toByteArray();}public Object deserialize(byte[] by) throws Exception {if(by==null) throw new NullPointerException();ByteArrayInputStream is = new ByteArrayInputStream(by);ObjectInputStream in = new ObjectInputStream(is);return in.readObject();}
2)对象序列化--hessian (hessian2的序列化方式在附件中)
public byte[] serialize(Object obj) throws IOException{if(obj==null) throw new NullPointerException();ByteArrayOutputStream os = new ByteArrayOutputStream();HessianOutput ho = new HessianOutput(os);ho.writeObject(obj);return os.toByteArray();}public Object deserialize(byte[] by) throws IOException{if(by==null) throw new NullPointerException();ByteArrayInputStream is = new ByteArrayInputStream(by);HessianInput hi = new HessianInput(is);return hi.readObject();}
从以上代码不难看出,对象序列化的过程为:
先将对象转为字节码或其它,然后再将其还原为对象。在反序列化时,内存中必须有源对象的所属类。
3、对象序列化效率
hessian2在这方面有了很大的改进,所以优势十分明显。具体细节不再详述,在进阶篇中,我会详述序列化的实现细节。在此仅把实例执行结果公布出来:
java:77stxmhessian:41stxmhessian2:30stxm说明:1、数字为对象序列化后的字节长度。2、‘stxm’为对象方法的执行结果。
hessian2的优点,谁用谁知道。待我再做深入研究之后,再把我自己认为的和大家认为的优点总结一下,并加以解释。
页:
[1]