Skip to content

Instantly share code, notes, and snippets.

@zhuhai
Created June 3, 2016 10:04
Show Gist options
  • Save zhuhai/6a48958cf3d7ff86a27c29bbd765b243 to your computer and use it in GitHub Desktop.
Save zhuhai/6a48958cf3d7ff86a27c29bbd765b243 to your computer and use it in GitHub Desktop.
使用protostuff进行序列化和反序列化
/**
* Created by zhuhai on 2016/6/3.
*/
public class ProtostuffUtil {
private static Map<Class<?>, Schema<?>> schemaMap = new ConcurrentHashMap<Class<?>, Schema<?>>();
public static <T> Schema<T> getSchema(Class<T> clazz) {
Schema<T> schema = (Schema<T>) schemaMap.get(clazz);
if (schema == null) {
schema = RuntimeSchema.getSchema(clazz);
if (schema != null) {
schemaMap.put(clazz, schema);
}
}
return schema;
}
/**
* 序列化
* @param obj
* @param <T>
* @return
*/
public static <T> byte[] serializer(T obj) {
Class<T> clazz = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(clazz);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 反序列化
* @param data
* @param clazz
* @param <T>
* @return
*/
public static <T> T deserializer(byte[] data, Class<T> clazz) {
try {
T obj = clazz.newInstance();
Schema<T> schema = getSchema(clazz);
ProtostuffIOUtil.mergeFrom(data, obj, schema);
return obj;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment