如果我只知道其描述符,我怎样才能获得protobuf消息的默认实例:
Descriptor descriptor = SomeOuterMessage.getDescriptor()
.findNestedTypeByName("InnerMessageName");
Message defaultInstance = descriptor. <???> // how do I get an instance of "InnerMessageName"?
答案 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();