How to set duplicate fields in protobuf before creating a message?

When I got something like

Message Foo{
    repeated Bar bar = 1;
}

Now I want to insert xy objects in Bar. Each of them is created in a loop.

for(i=0; i < xy ; i++){
    //Add Bar into foo
}
//Build foo after loop

Is this possible or do I need all the xy bar fields before creating the foo object?

+4
source share
1 answer

When you use the protoc command to create a java object, it will create a Foo object that will have its own build method on it.

You end up with something like this

//Creates the builder object 
Builder builder = Package.Foo.newBuilder();
//populate the repeated field.
builder.addAll(new ArrayList<Bar>());
//This should build out a Foo object
builder.build(); 

To add individual objects, you can do something like this.

    Bar bar = new Bar();
    builder.addBar(bar);
    builder.build();

Edited using the use case you requested.

+6
source

All Articles