栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

基于Protostuff的序列化与反序列化

基于Protostuff的序列化与反序列化

一种protobuf序列化方式,不需要编写proto文件 Maven依赖
         
            com.dyuproject.protostuff
            protostuff-core
            1.0.7
        

        
            com.dyuproject.protostuff
            protostuff-runtime
            1.0.7
        
实现
public class SerializingUtil {

    
    public static  byte[] serialize(T source) {
        RuntimeSchema schema;
        linkedBuffer buffer = null;
        byte[] result;
        try {
            schema = RuntimeSchema.createFrom((Class) source.getClass());
            buffer = linkedBuffer.allocate(linkedBuffer.DEFAULT_BUFFER_SIZE);
            result = ProtostuffIOUtil.toByteArray(source, schema, buffer);
        } catch (Exception e) {
            throw new RuntimeException("serialize exception");
        } finally {
            if (buffer != null) {
                buffer.clear();
            }
        }

        return result;
    }

    
    public static  T deserialize(byte[] source, Class typeClass) {
        RuntimeSchema schema;
        T newInstance;
        try {
            schema = RuntimeSchema.createFrom(typeClass);
            newInstance = typeClass.newInstance();
            ProtostuffIOUtil.mergeFrom(source, newInstance, schema);
        } catch (Exception e) {
            throw new RuntimeException("deserialize exception");
        }

        return newInstance;
    }
}
测试类
public class SerializingUtilTest {

    public static void main(String[] args) {
        String expect = "hello, world.";

        byte[] bytes = SerializingUtil.serialize(expect);
        System.out.println(bytes);

        String s = SerializingUtil.deserialize(bytes, String.class);
        System.out.println(s);
    }
}

原文:基于Protostuff的序列化与反序列化

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650426.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号