package com.sdyc.ndmp.protobuf.serializer;
import com.google.protobuf.GeneratedMessage;
import java.lang.reflect.Method;
/**
*
*
* Created by IntelliJ IDEA.
* User: zhenqin
* Date: 14-7-28
* Time: 下午3:36
* To change this template use File | Settings | File Templates.
*
*
*
* @author zhenqin
*/
public class ProtobufClassSerializer implements Serializer {
/**
* 字符编码
*/
protected String charset = "UTF-8";
protected final Class extends GeneratedMessage> objectClass;
protected Method parseMethod;
public ProtobufClassSerializer(Class extends GeneratedMessage> objectClass) {
this(objectClass, "UTF-8");
}
public ProtobufClassSerializer(Class extends GeneratedMessage> objectClass, String charset) {
this.charset = charset;
this.objectClass = objectClass;
}
@Override
public byte[] serialize(GeneratedMessage o) {
if (o == null) {
return null;
}
return o.toByteArray();
}
@Override
public GeneratedMessage deserialize(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
// 检查一下Netty Protobuf解码器是怎么写的
try {
if (parseMethod == null) {
parseMethod = objectClass.getMethod("parseFrom", byte[].class);
}
return (GeneratedMessage) parseMethod.invoke(null, bytes);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("class: " + objectClass.getName() + " has not method: parseFrom(byte[]).", e);
} catch (Exception e) {
throw new IllegalStateException("reflection error!", e);
}
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
}