大家好,又见面了,我是你们的朋友全栈君。
protostuff,是google在原来的protobuffer是的优化产品。使用起来也比较简单易用,目前效率也是最好的一种序列化工具。
pom:
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.4.0</version>
</dependency>
package cn.witsky.utils;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProtostuffUtils {
/**
* 将指定对象序列化为byte数组
* @param source
* @param <T>
* @return
*/
public static <T> byte[] serialize(T source) {
LinkedBuffer buffer = null;
try {
RuntimeSchema<T> schema = RuntimeSchema.createFrom((Class<T>) source.getClass());
buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
return ProtostuffIOUtil.toByteArray(source, schema, buffer);
} catch (Exception e) {
throw new RuntimeException("ProtostuffUtils serialize exception");
} finally {
if (buffer != null) {
buffer.clear();
}
}
}
/**
* 将byte数组反序列化为指定对象
* @param source
* @param typeClass
* @param <T>
* @return
*/
public static <T> T deserialize(byte[] source, Class<T> typeClass) {
try {
RuntimeSchema<T> schema = RuntimeSchema.createFrom(typeClass);
T newInstance = typeClass.newInstance();
ProtostuffIOUtil.mergeFrom(source, newInstance, schema);
return newInstance;
} catch (Exception e) {
throw new RuntimeException("ProtostuffUtils deserialize exception");
}
}
public static void main(String[] args) throws Exception {
Test expect = new Test();
expect.setA("gacl");
expect.setB("男");
expect.setC(1);
byte[] serialized = serialize(expect);
System.out.println(deserialize(serialized, Test.class));
System.out.println(deserialize(serialized, Test.class).equals(expect));
// Assert.assertEquals(deserialize(serialized, String.class), expect);
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/133991.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...