ProtoLiteUtils { public static <T extends MessageLite> Metadata.BinaryMarshaller<T> metadataMarshaller( final T instance) { return new Metadata.BinaryMarshaller<T>() { @Override public byte[] toBytes(T value) { return value.toByteArray(); } @Override @SuppressWarnings("unchecked") public T parseBytes(byte[] serialized) { try { return (T) instance.getParserForType().parseFrom(serialized, globalRegistry); } catch (InvalidProtocolBufferException ipbe) { throw new IllegalArgumentException(ipbe); } } }; } private  ProtoLiteUtils(); @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1787") static void setExtensionRegistry(ExtensionRegistryLite newRegistry); static Marshaller<T> marshaller(final T defaultInstance); static Metadata.BinaryMarshaller<T> metadataMarshaller(
      final T instance);  }
@Test public void metadataMarshaller_roundtrip() { Metadata.BinaryMarshaller<Type> metadataMarshaller = ProtoLiteUtils.metadataMarshaller(Type.getDefaultInstance()); assertEquals(proto, metadataMarshaller.parseBytes(metadataMarshaller.toBytes(proto))); }
@Test public void metadataMarshaller_invalid() { Metadata.BinaryMarshaller<Type> metadataMarshaller = ProtoLiteUtils.metadataMarshaller(Type.getDefaultInstance()); try { metadataMarshaller.parseBytes(new byte[] {-127}); fail("Expected exception"); } catch (IllegalArgumentException ex) { assertNotNull(((InvalidProtocolBufferException) ex.getCause()).getUnfinishedMessage()); } }