1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- package com.sdyc.ndmp.protobuf.serializer;
- import com.google.protobuf.GeneratedMessage;
- import java.lang.reflect.Method;
- /**
- * <pre>
- *
- * Created by IntelliJ IDEA.
- * User: zhenqin
- * Date: 14-7-28
- * Time: 下午3:36
- * To change this template use File | Settings | File Templates.
- *
- * </pre>
- *
- * @author zhenqin
- */
- public class ProtobufClassSerializer implements Serializer<GeneratedMessage> {
- /**
- * 字符编码
- */
- 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;
- }
- }
|