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(); } } }