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();
source share