基于Protostuff的序列化与反序列化
Posted mada26
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Protostuff的序列化与反序列化相关的知识,希望对你有一定的参考价值。
一种protobuf序列化方式,不需要编写proto文件
Maven依赖
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.7</version>
</dependency>
实现
public class SerializingUtil
/**
* 将目标类序列化为byte数组
*
* @param source
* @param <T>
* @return
*/
public static <T> byte[] serialize(T source)
RuntimeSchema<T> schema;
LinkedBuffer buffer = null;
byte[] result;
try
schema = RuntimeSchema.createFrom((Class<T>) 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;
/**
* 将byte数组反序列化为目标类
*
* @param source
* @param typeClass
* @param <T>
* @return
*/
public static <T> T deserialize(byte[] source, Class<T> typeClass)
RuntimeSchema<T> 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的序列化与反序列化的主要内容,如果未能解决你的问题,请参考以下文章