亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

protostuff基本使用

標簽:
JQuery

[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

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消