protostuff基本使用[通俗易懂]

protostuff基本使用[通俗易懂][toc]protostuff基本使用protostuff基于GoogleProtobuf,好处就是不用自己写.proto文件即可实现对象的序列化与反序列化,下面给出示例代码。程序代码User.javapackagecn.xpleaf.pojo;publicclassUser{privateStringname;privateintage;…

大家好,又见面了,我是你们的朋友全栈君。

[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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/144116.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号