java 如何在构建消息之前在protobuf中设置重复字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29170183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set repeated fields in protobuf before building the message?
提问by Gobliins
When i got something like
当我得到类似的东西
Message Foo{
repeated Bar bar = 1;
}
Now i want to insert xy objects of Bar. Each is created in a loop.
现在我想插入 Bar 的 xy 对象。每个都是在一个循环中创建的。
for(i=0; i < xy ; i++){
//Add Bar into foo
}
//Build foo after loop
Is this possible or do i need all xy bar fields at the same time before building the foo Object?
这是可能的还是在构建 foo 对象之前我需要所有 xy bar 字段?
回答by Venki
When you use the protoc command to generate the java object it will create a Foo Object which will have its own builder method on it.
当您使用 protoc 命令生成 java 对象时,它将创建一个 Foo 对象,该对象将拥有自己的构建器方法。
You will end up doing 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 with the use case you've requested.
使用您请求的用例进行编辑。