protostuff 工具类

protostuff,是google在原来的protobuffer是的优化产品。使用起来也比较简单易用,目前效率也是最好的一种序列化工具。
                pom:
                <dependency>
                  <groupId>io.protostuff</groupId>
                  <artifactId>protostuff-core</artifactId>
                  <version>1.4.0</version>
                </dependency>
                <dependency>
                  <groupId>io.protostuff</groupId>
                  <artifactId>protostuff-runtime</artifactId>
                  <version>1.4.0</version>
                </dependency>

 

package cn.witsky.utils;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProtostuffUtils {

    /**
     * 将指定对象序列化为byte数组
     * @param source
     * @param <T>
     * @return
     */
    public static <T> byte[] serialize(T source) {
        LinkedBuffer buffer = null;
        try {
            RuntimeSchema<T> schema = RuntimeSchema.createFrom((Class<T>) source.getClass());
            buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
            return ProtostuffIOUtil.toByteArray(source, schema, buffer);
        } catch (Exception e) {
            throw new RuntimeException("ProtostuffUtils serialize exception");
        } finally {
            if (buffer != null) {
                buffer.clear();
            }
        }
    }

    /**
     * 将byte数组反序列化为指定对象
     * @param source
     * @param typeClass
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] source, Class<T> typeClass) {
        try {
            RuntimeSchema<T> schema = RuntimeSchema.createFrom(typeClass);
            T newInstance = typeClass.newInstance();
            ProtostuffIOUtil.mergeFrom(source, newInstance, schema);
            return newInstance;
        } catch (Exception e) {
            throw new RuntimeException("ProtostuffUtils deserialize exception");
        }
    }

    public static void main(String[] args) throws Exception {
        Test expect = new Test();
        expect.setA("gacl");
        expect.setB("男");
        expect.setC(1);
        byte[] serialized = serialize(expect);
        System.out.println(deserialize(serialized, Test.class));
        System.out.println(deserialize(serialized, Test.class).equals(expect));
//        Assert.assertEquals(deserialize(serialized, String.class), expect);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值