ProtobufClassSerializer.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.sdyc.ndmp.protobuf.serializer;
  2. import com.google.protobuf.GeneratedMessage;
  3. import java.lang.reflect.Method;
  4. /**
  5. * <pre>
  6. *
  7. * Created by IntelliJ IDEA.
  8. * User: zhenqin
  9. * Date: 14-7-28
  10. * Time: 下午3:36
  11. * To change this template use File | Settings | File Templates.
  12. *
  13. * </pre>
  14. *
  15. * @author zhenqin
  16. */
  17. public class ProtobufClassSerializer implements Serializer<GeneratedMessage> {
  18. /**
  19. * 字符编码
  20. */
  21. protected String charset = "UTF-8";
  22. protected final Class<? extends GeneratedMessage> objectClass;
  23. protected Method parseMethod;
  24. public ProtobufClassSerializer(Class<? extends GeneratedMessage> objectClass) {
  25. this(objectClass, "UTF-8");
  26. }
  27. public ProtobufClassSerializer(Class<? extends GeneratedMessage> objectClass, String charset) {
  28. this.charset = charset;
  29. this.objectClass = objectClass;
  30. }
  31. @Override
  32. public byte[] serialize(GeneratedMessage o) {
  33. if (o == null) {
  34. return null;
  35. }
  36. return o.toByteArray();
  37. }
  38. @Override
  39. public GeneratedMessage deserialize(byte[] bytes) {
  40. if (bytes == null || bytes.length == 0) {
  41. return null;
  42. }
  43. // 检查一下Netty Protobuf解码器是怎么写的
  44. try {
  45. if (parseMethod == null) {
  46. parseMethod = objectClass.getMethod("parseFrom", byte[].class);
  47. }
  48. return (GeneratedMessage) parseMethod.invoke(null, bytes);
  49. } catch (NoSuchMethodException e) {
  50. throw new IllegalStateException("class: " + objectClass.getName() + " has not method: parseFrom(byte[]).", e);
  51. } catch (Exception e) {
  52. throw new IllegalStateException("reflection error!", e);
  53. }
  54. }
  55. public String getCharset() {
  56. return charset;
  57. }
  58. public void setCharset(String charset) {
  59. this.charset = charset;
  60. }
  61. }