
实现com.dyuproject.protostuff protostuff-core1.0.7 com.dyuproject.protostuff protostuff-runtime1.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的序列化与反序列化
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)