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

Marco Faustinelli picture Marco Faustinelli · Jun 28, 2016 · Viewed 22.6k times · Source

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" :-)

Answer

Wilson picture Wilson · Jun 28, 2016

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