com.github.linshenkx.rpcnettycommon.serialization.serializer.impl.ProtocolBufferSerializer Maven / Gradle / Ivy
package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
import org.apache.commons.lang3.reflect.MethodUtils;
/**
* @version V1.0
* @author: lin_shen
* @date: 2018/11/18
* @Description: ProtocolBuffer序列化(只能序列化IDL产生的类)
*/
public class ProtocolBufferSerializer implements ISerializer {
@Override
public byte[] serialize(T obj) {
try {
return (byte[]) MethodUtils.invokeMethod(obj, "toByteArray");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public T deserialize(byte[] data, Class cls) {
try {
Object o = MethodUtils.invokeStaticMethod(cls, "getDefaultInstance");
return (T) MethodUtils.invokeMethod(o, "parseFrom", new Object[]{data});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}