ProtobufUtils { public static Message parseFrom(InputStream inputStream, Class clazz) { try { Method method = clazz.getMethod("getDefaultInstance"); Message proto = (Message) method.invoke(null); proto = proto.newBuilderForType().mergeFrom(inputStream).build(); return proto; } catch (Exception ex) { String errorMsg = String.format("parse proto failed, msg=%s", ex.getMessage()); log.error(errorMsg); throw new RuntimeException(errorMsg); } }  static MessageType getMessageType(Method method); static Message parseFrom(InputStream inputStream, Class clazz); static Message parseFrom(byte[] inputBytes, Class clazz); static Message parseFrom(ByteBuf input, Message defaultInstance); static Message parseFrom(byte[] input, Message defaultInstance); static Message parseFrom(DynamicCompositeByteBuf input, Message defaultInstance);  }
@Test public void testParseFrom() { Echo.EchoRequest request = Echo.EchoRequest.newBuilder().setMessage("hello").build(); byte[] bytes = request.toByteArray(); Echo.EchoRequest request1 = (Echo.EchoRequest) ProtobufUtils.parseFrom(bytes, request.getClass()); Assert.assertTrue(request1.getMessage().equals(request.getMessage())); }
@Test public void testParseFrom2() { Echo.EchoRequest request = Echo.EchoRequest.newBuilder().setMessage("hello").build(); byte[] bytes = request.toByteArray(); InputStream inputStream = new ByteBufInputStream(Unpooled.wrappedBuffer(bytes)); Echo.EchoRequest request1 = (Echo.EchoRequest) ProtobufUtils.parseFrom(inputStream, request.getClass()); Assert.assertTrue(request1.getMessage().equals(request.getMessage())); }
@Test public void testParseFrom3() throws IOException { Echo.EchoRequest request = Echo.EchoRequest.newBuilder().setMessage("hello").build(); byte[] bytes = request.toByteArray(); ByteBuf buf = Unpooled.wrappedBuffer(bytes); Message defaultInstance = request.getDefaultInstanceForType(); Echo.EchoRequest request1 = (Echo.EchoRequest) ProtobufUtils.parseFrom(buf, defaultInstance); Assert.assertTrue(request1.getMessage().equals(request.getMessage())); }
@Test public void testParseFrom4() throws IOException { Echo.EchoRequest request = Echo.EchoRequest.newBuilder().setMessage("hello").build(); byte[] bytes = request.toByteArray(); ByteBuf buf = Unpooled.wrappedBuffer(bytes); DynamicCompositeByteBuf compositeByteBuf = new DynamicCompositeByteBuf(buf); Message defaultInstance = request.getDefaultInstanceForType(); Echo.EchoRequest request1 = (Echo.EchoRequest) ProtobufUtils.parseFrom(compositeByteBuf, defaultInstance); Assert.assertTrue(request1.getMessage().equals(request.getMessage())); }