【问题标题】:How to set repeated fields in protobuf before building the message?如何在构建消息之前在 protobuf 中设置重复字段?
【发布时间】:2015-03-20 15:28:47
【问题描述】:

假设我有一个包含重复字段的消息:

Message Foo {
    repeated Bar bar = 1;
}

现在我想将nBar 对象插入到字段栏中,每个对象都是在循环中创建的。

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

这可能吗,还是在构建 foo 对象之前我需要所有 n bar 字段?

【问题讨论】:

    标签: java protocol-buffers


    【解决方案1】:

    当您使用 protoc 命令生成 java 对象时,它将创建一个 Foo 对象,该对象将具有自己的构建器方法。

    你最终会做这样的事情

    //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(); 
    

    要添加单个对象,您可以执行以下操作。

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

    根据您要求的用例进行编辑。

    【讨论】:

    • 是的,这就是我现在所做的,但我希望能找到可以一个一个插入内部对象的东西。
    • 编辑了消息,应该有一个选项可以一一传入各个对象。
    • 单线如何做到这一点?
    【解决方案2】:
    List<Bar> barList= new Arraylist();
    barList.add(new Bar());
    

    然后在 Foo 中设置 Bar 的列表

    Foo foo =  Foo.newBuilder()
            .addAllBar(barList)
            .build;
    

    Bar 只能设置一个值

    Foo foo =  Foo.newBuilder()
            .addBar(new Bar())
            .build;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多