protostuff基本使用

[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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值