How do I get a multi-line protobuf builder in Java?
I want to convert a different format object to protobuf knowing the protobuf descriptors. It's easy to do this for regular fields or even a nested field. But I ran into a problem for duplicate fields.
message Foo {
optional MsgA a = 1;
repeated MsgB b = 2;
}
For "MsgA a" the bld.getFieldBuilder code (field) works:
Foo.Builder bld = Foo.newBuilder();
Descriptors.Descriptor msgDesc = Foo.getDescriptor();
List<Descriptors.FieldDescriptor> fields = msgDesc.getFields();
for (Descriptors.FieldDescriptor field : fields) {
Message.Builder subBld = bld.getFieldBuilder(field);
// set foreign value xyz using subBld
// subBld.setFleld(subfield1, xyz);
}
But for "MsgB b" the same code throws "UnsupportedOperationException: getFieldBuilder () called on non-message type".
I understand that the repeating field is a list, I can set each one separately. But how do I create a builder first? Is there a simple and easy way to do this?
Thanks for any input.
source to share
You don't have a creator for the repeating field - you are calling Builder.addRepeatedField(field, value)
etc. To get a builder for a repeating field type, you can use:
Builder builder = bld.newBuilderForField(field)
If you want to change an existing value, you can use Builder.getRepeatedFieldBuilder(field, index)
.
To instantiate to begin with, you can use Builder.newBuilderForField
:
Message.Builder subBld = bld.newBuilderForField(field);
// Now modify subBld, then...
bld.addRepeatedField(field, subBld.build());
source to share