提交 0d7fd600 编写于 作者: U ujued

serialize fix

上级 68eb30f2
...@@ -30,39 +30,37 @@ import java.io.ByteArrayOutputStream; ...@@ -30,39 +30,37 @@ import java.io.ByteArrayOutputStream;
/** /**
* @author lorne 2017/11/11 * @author lorne 2017/11/11
*/ */
@SuppressWarnings("unchecked")
public class ProtostuffSerializer implements ISerializer { public class ProtostuffSerializer implements ISerializer {
private static final SchemaCache cachedSchema = SchemaCache.getInstance();
private static final Objenesis objenesis = new ObjenesisStd(true); private static final SchemaCache SCHEMA_CACHE = SchemaCache.getInstance();
private static final Objenesis OBJENESIS = new ObjenesisStd(true);
private static <T> Schema<T> getSchema(Class<T> cls) { private static <T> Schema<T> getSchema(Class<T> cls) {
return (Schema<T>) cachedSchema.get(cls); return (Schema<T>) SCHEMA_CACHE.get(cls);
} }
@Override @Override
public byte[] serialize(Object obj) throws SerializerException { public byte[] serialize(Object obj) throws SerializerException {
Class cls = obj.getClass(); Class cls = obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){
try {
Schema schema = getSchema(cls); Schema schema = getSchema(cls);
ProtostuffIOUtil.writeTo(outputStream, obj, schema, buffer); ProtostuffIOUtil.writeTo(outputStream, obj, schema, buffer);
return outputStream.toByteArray();
} catch (Exception e) { } catch (Exception e) {
throw new SerializerException(e.getMessage(), e); throw new SerializerException(e.getMessage(), e);
} finally { } finally {
buffer.clear(); buffer.clear();
} }
return outputStream.toByteArray();
} }
@Override @Override
public <T> T deSerialize(byte[] param, Class<T> clazz) throws SerializerException { public <T> T deSerialize(byte[] param, Class<T> cls) throws SerializerException {
T object; T object;
try { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(param)) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(param); object = OBJENESIS.newInstance(cls);
Class cls = clazz;
object = objenesis.newInstance((Class<T>) cls);
Schema schema = getSchema(cls); Schema schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(inputStream, object, schema); ProtostuffIOUtil.mergeFrom(inputStream, object, schema);
return object; return object;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册