首页 > 代码库 > 【java】序列化反序列化

【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;
   }

 

【java】序列化反序列化