从protobuf描述符获取默认实例

时间:2017-09-21 07:43:33

标签: java protocol-buffers

如果我只知道其描述符,我怎样才能获得protobuf消息的默认实例:

Descriptor descriptor   = SomeOuterMessage.getDescriptor()
                              .findNestedTypeByName("InnerMessageName");
Message defaultInstance = descriptor. <???> // how do I get an instance of "InnerMessageName"?

1 个答案:

答案 0 :(得分:1)

您可以通过DynamicMessage类获取默认实例。

说一个像下面这样的原型:

Message PhoneBook {
    repeated Person people = 1;
}
Message Person {
    required Name name = 1;
    optional String phone = 2;
}
Message Name {
    required String family_name = 1;
    required String given_name = 2;
}

获取People的默认实例的代码如下:

PhoneBook phoneBook = phoneBook.getDefaultInstance();
Descriptors.Descriptor personDescriptor = phoneBook.getDescriptor().findNestedTypeByName("people");
DynamicMessage defaultPeopleInstance = DynamicMessage.newBuilder(personDescriptor).getDefaultInstanceForType().build();
assert defaultPeopleInstance == People.getDefaultInstance();