zoukankan      html  css  js  c++  java
  • ProtobufUtils

    import java.io.IOException;
    import java.io.InputStream;
    import java.lang.reflect.Method;
    
    import com.google.protobuf.Message;
    import com.google.protobuf.Message.Builder;
    import com.yundaex.common.exception.WrappedReflectException;
    
    public class ProtobufUtils {
        
        public static <T> byte[] marshal(T graph) {
            if(Message.class.isAssignableFrom(graph.getClass())) {
                Message msg = ((Message)graph);
                return msg.toByteArray();
            } else {
                throw new ProtobufParseException();
            }
        }
    
        @SuppressWarnings("unchecked")
        public static <T> T unmarshal(InputStream inputStream,Class<T> clazz) {
            Message instance = generateDefaultInstance(clazz);
            Builder builder = null;
            try {
                builder = instance.newBuilderForType().mergeFrom(inputStream);
            } catch (IOException e) {
                throw new ProtobufParseException();
            }
            if (!builder.isInitialized()) {
                // TODO which exception should be thrown here?
                throw new ProtobufParseException();
            }
            return (T) builder.build();
        }
        
        @SuppressWarnings("unchecked")
           public static <T> T unmarshal(byte[] data,Class<T> clazz) {
            Message instance = generateDefaultInstance(clazz);
            Builder builder = null;
               try {
                   builder = instance.newBuilderForType().mergeFrom(data);
               } catch (IOException e) {
                   throw new ProtobufParseException();
               }
            if (!builder.isInitialized()) {
               // TODO which exception should be thrown here?
               throw new ProtobufParseException();
            }
            return (T) builder.build();
         }
        
        private static <T> Message generateDefaultInstance(Class<T> instanceClass) {
              if (Message.class.isAssignableFrom(instanceClass)) {
                  try {
                      Method method = instanceClass.getMethod("getDefaultInstance", new Class[0]);
                      return (Message) method.invoke(null, new Object[0]);
                  } catch (Exception ex) {
                      throw new WrappedReflectException();
                  }
              } else {
                  throw new WrappedReflectException();
              }
          }
    }
  • 相关阅读:
    java接口返回json数据格式
    ajax请求报406问题
    ajax跨域问题
    js、css等引入文件路径正确,却报404的解决办法
    HttpServletResponse,HttpServletRequest详解
    python学习(十六)os使用
    python学习(十五)python读取配置yaml
    python学习(十四)python操作发送邮件(163邮箱)
    python学习(十三)python使用pymsql链接数据库操作
    python学习(十二)python正则表达式
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/6543972.html
Copyright © 2011-2022 走看看