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();
              }
          }
    }
  • 相关阅读:
    MySQL多表查询回顾
    本地SQL查询
    QBC查询
    HQL查询
    Hibernate多对多操作
    Hibernate一对多操作
    表与表之间关系回顾
    x$bh视图
    dba 和 rdba 转载
    What you can talk
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/6543972.html
Copyright © 2011-2022 走看看