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

基于Protostuff的序列化与反序列化,第1张

基于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的序列化与反序列化

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5652571.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存