Is there a way to write proto data without generating code?

I would like to know if the reflection API provided by google protobuf can be used to serialize messages without generating code?

The protocol buffer allows us to use reflection on Message or Message.Builder objects after the parsing process . But in my case, I would like to know if I can fill this object with fields / values, and then write them to a file.

+8
source share
1 answer

CodedOutputStream

One way to do this is to understand how the message is encoded, and use CodedOutputStream to write message fields using the appropriate write*() methods.

For instance. write the following message:

 message MyMessage { int foo = 1; string bar = 2; } 

You would use this piece of code:

 ByteArrayOutputStream baos = new ByteArrayOutputStream(); CodedOutputStream out = CodedOutputStream.newInstance(baos); out.writeInt32(1, 1); out.writeString(2, "s"); out.flush(); byte[] rawProtocolBuffer = baos.toByteArray(); 

Dynamicmessage

Another way is to create descriptors manually and then use DynamicMessage to set the appropriate fields, but this is more boilerplate than using CodedOutputStream directly.

 String messageName = "MyMessage"; FileDescriptorProto fileDescriptorProto = FileDescriptorProto .newBuilder() .addMessageType(DescriptorProto.newBuilder() .setName(messageName) .addField(FieldDescriptorProto.newBuilder() .setName("foo") .setNumber(1) .setType(FieldDescriptorProto.Type.TYPE_INT32) .build()) .addField(FieldDescriptorProto.newBuilder() .setName("bar") .setNumber(2) .setType(FieldDescriptorProto.Type.TYPE_STRING) .build()) .build()) .build(); Descriptor messageDescriptor = FileDescriptor .buildFrom(fileDescriptorProto, new FileDescriptor[0]) .findMessageTypeByName(messageName); DynamicMessage message = DynamicMessage .newBuilder(messageDescriptor) .setField(messageDescriptor.findFieldByNumber(1), 1) .setField(messageDescriptor.findFieldByName("bar"), "s") .build(); byte[] rawProtocolBuffer = message.toByteArray(); 
+1
source

Source: https://habr.com/ru/post/948044/


All Articles