Examining a protobuf message - how to get field values by name?

可紊 提交于 2019-12-22 01:43:46

问题


I seem unable to find a way to verify the value of a field inside a protobuf message without explicitly invoking its getter.

I see examples around that make usage of Descriptors.FieldDescriptor instances to reach inside the message map, but they are either iterator-based or driven by field number.

Once I have the map:

Map<Descriptors.FieldDescriptor, Object> allFields = myMsg.getAllFields();

how can I get the value of field "fieldXyz"?

I know that I can use myMsg.getFieldXyz(), but this is not usable in a systematic way.

If there is no way to access field values by their names, I'd like to know what is the rationale behind this choice. I may have still to understand the protobuf "philosophy" :-)


回答1:


I am not sure you are looking for Descriptors#findFieldByName(name). You can try with followings:

FieldDescriptor fieldDescriptor = message.getDescriptorForType().findFieldByName("fieldXyz");
Object value = message.getField(fieldDescriptor);



回答2:


I know this is tagged for java but incase anyone is looking for a way to get the value in c++: (Assuming: field = FieldDescriptor* which contains a int32)

    int32_t value = message_1.GetReflection()->GetInt32(message_1, field);

It took me a while to get this and didn't find any stackoverflow references hence adding it. Hope it helps. Thanks!



来源:https://stackoverflow.com/questions/38071689/examining-a-protobuf-message-how-to-get-field-values-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!