码迷,mamicode.com
首页 > 其他好文 > 详细

protostuff基本使用

时间:2018-02-16 22:33:54      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:tag   pojo   sage   方法   使用   bytes   message   字节数组   数组   

[toc]


protostuff基本使用

protostuff基于Google Protobuf,好处就是不用自己写.proto文件即可实现对象的序列化与反序列化,下面给出示例代码。

程序代码

User.java

package cn.xpleaf.pojo;

public class User {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + "]";
    }

}

UserSerializationUtil.java

package cn.xpleaf.protostuff;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

import cn.xpleaf.pojo.User;

public class UserSerializationUtil {

    private static RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);

    /**
     * 序列化方法,将User对象序列化为字节数组
     * @param user
     * @return
     */
    public static byte[] serialize(User user) {
        // Serializes the {@code message} into a byte array using the given schema
        return ProtostuffIOUtil.toByteArray(user, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
    }

    /**
     * 反序列化方法,将字节数组反序列化为User对象
     * @param array
     * @return
     */
    public static User deserialize(byte[] array) {
        User user = schema.newMessage();
        // Merges the {@code message} with the byte array using the given {@code schema}
        ProtostuffIOUtil.mergeFrom(array, user, schema);
        return user;
    }
}

Demo.java

package cn.xpleaf.protostuff;

import cn.xpleaf.pojo.User;

public class Demo {
    public static void main(String[] args) {
        // 创建User对象
        User user = new User();
        user.setName("xpleaf");
        user.setAge(10);
        System.out.println("序列化前:" + user);
        // 使用UserSerializationUtil将user对象序列化
        byte[] userBytes = UserSerializationUtil.serialize(user);
        // 使用UserSerializationUtil反序列化字节数组为user对象
        User user2 = UserSerializationUtil.deserialize(userBytes);
        System.out.println("序列化后再反序列化:" + user2);
        // 判断值是否相等
        System.out.println(user.toString().equals(user2.toString()));
    }
}

测试

执行demo代码,输出如下:

序列化前:User [name=xpleaf, age=10]
序列化后再反序列化:User [name=xpleaf, age=10]
true

protostuff基本使用

标签:tag   pojo   sage   方法   使用   bytes   message   字节数组   数组   

原文地址:http://blog.51cto.com/xpleaf/2071748

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!