【java】序列化反序列化

通过Protostuff进行序列化和反序列号

  /**
     * 把MessageBody对象序列化为byte[] {@link MessageBody}
     *
     * @param MessageBody
     * @return
     */
    public static byte[] serializeMessageBody(MessageBody messageBody) {
         byte[] bytes = null;
       Schema<MessageBody> schema = RuntimeSchema.getSchema(MessageBody.class);
       LinkedBuffer buffer = LinkedBuffer.allocate(4096);
       try {
            bytes = ProtostuffIOUtil.toByteArray(messageBody, schema, buffer);
       } finally {
           buffer.clear();
       }
       return bytes;
   }

    /**
     * 反序列化,把byte[]转成MessageBody对象
     *
     * @param bytes
     * @return
     */
    public static MessageBody deserializeMessageBody(byte[] bytes) {
       MessageBody messageBody = new MessageBody();
       Schema<MessageBody> schema = RuntimeSchema.getSchema(MessageBody.class);
       ProtostuffIOUtil.mergeFrom(bytes, messageBody, schema);
       return messageBody;
   }

 

posted @ 2016-12-29 10:10  hm_zhang  阅读(126)  评论(0编辑  收藏  举报