检查 protobuf 消息 - 如何按名称获取字段值? [英] Examining a protobuf message - how to get field values by name?
问题描述
如果不显式调用 getter,我似乎无法找到一种方法来验证 protobuf 消息中字段的值.
I seem unable to find a way to verify the value of a field inside a protobuf message without explicitly invoking its getter.
我看到了一些使用 Descriptors.FieldDescriptor
实例到达消息映射内部的例子,但它们要么基于迭代器,要么由字段编号驱动.
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.
一旦我有了地图:
Map<Descriptors.FieldDescriptor, Object> allFields = myMsg.getAllFields();
如何获取"fieldXyz"
字段的值?
我知道我可以使用 myMsg.getFieldXyz()
,但这不能以系统的方式使用.
I know that I can use myMsg.getFieldXyz()
, but this is not usable in a systematic way.
如果无法通过名称访问字段值,我想知道这种选择背后的基本原理是什么.我可能仍然需要了解 protobuf 的哲学":-)
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" :-)
推荐答案
我不确定您是否在寻找 Descriptors#findFieldByName(name)
.您可以尝试以下操作:
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);
这篇关于检查 protobuf 消息 - 如何按名称获取字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!