How to get a protobuf repeated field builder in Java?

I want to convert an object of another format into a protobuf, knowing the protobuf's Descriptors. It's easy to do for regular fields or even a nested field. But, I'm running into a problem for repeated fields.

message Foo {
    optional MsgA a = 1;
    repeated MsgB b = 2;
}

For "MsgA a", the code bld.getFieldBuilder(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 a non-Message type."

I understand the repeated field is a list, I may set each one separately. But, how do I get a builder first? Is there a clean and easy way to do the similar?

Thanks for any input.

Jon Skeet
people
quotationmark

You don't get a builder for the repeated field itself - you call Builder.addRepeatedField(field, value) etc. To get a builder for the type of the repeated field, you can use:

Builder builder = bld.newBuilderForField(field)

If you want to modify an existing value, you can use Builder.getRepeatedFieldBuilder(field, index).

To create an instance to start with, you can use Builder.newBuilderForField:

Message.Builder subBld = bld.newBuilderForField(field);
// Now modify subBld, then...
bld.addRepeatedField(field, subBld.build());

people

See more on this question at Stackoverflow