Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 741
Marco Faustinelli Avatar asked Jun 28 '16 09:06

Marco Faustinelli


People also ask

What is a descriptor in Protobuf?

descriptor. Descriptors essentially contain exactly the information found in a . proto file, in types that make this information accessible in Python.

What are the numbers in Protobuf?

In the binary format, the field number is combined with a type identifier. Field numbers from 1 to 15 can be encoded with their type as a single byte. Numbers from 16 to 2,047 take 2 bytes. You can go higher if you need more than 2,047 fields on a message for any reason.

How do you define an optional field in Protobuf 3?

The Best Answer is In proto3, all fields are "optional" (in that it is not an error if the sender fails to set them). But, fields are no longer "nullable", in that there's no way to tell the difference between a field being explicitly set to its default value vs. not having been set at all.

How do you comment in a proto file?

Adding Comments To add comments to your .proto files, use C/C++-style // and /* ... */ syntax.


1 Answers

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); 
like image 55
Wilson Avatar answered Oct 12 '22 04:10

Wilson