一种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 {
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;
}
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的序列化与反序列化