如何在java中设置google protobuf重复字段

时间:2015-08-18 19:53:34

标签: java protocol-buffers

这是我的定义

message point{
  optional float x = 1;
  optional float y = 2;
}
message test{
  repeated field point = 1;
}

在我的example.java文件中,我尝试按如下方式创建构建器:

for(i = 0; i < somearr.size(); i++)
{
    // I get x and y values from traversing the array 
    float x = getX;
    float y = getY;

    // now I want to set the repeated field point
}

如何设置重复的场点?

2 个答案:

答案 0 :(得分:3)

repeated PhoneNumber示例here非常相似。

将这些消息大写将有助于编码可读性。

message Point {
  optional float x = 1;
  optional float y = 2;
}
message Test {
  repeated Point point = 1;
}

的java:

Test.Builder b = Test.newBuilder();

for (i = 0; i < somearr.size(); i++) {
    float x = getX; // somehow?
    float y = getY; // ??
    b.addPoint(Point.newBuilder().setX(x).setY(y).build());
}

Test mytest = b.build();

答案 1 :(得分:2)

List<Point> points = ...;
Test.newBuilder().addAllPoint(points);