java 检查 protobuf 消息 - 如何按名称获取字段值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38071689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Examining a protobuf message - how to get field values by name?
提问by Marco Faustinelli
I seem unable to find a way to verify the value of a field inside a protobuf message without explicitly invoking its getter.
我似乎无法找到一种方法来验证 protobuf 消息中字段的值,而无需显式调用其 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.
我看到周围的示例使用Descriptors.FieldDescriptor
实例到达消息映射内部,但它们要么基于迭代器,要么由字段编号驱动。
Once I have the map:
一旦我有了地图:
Map<Descriptors.FieldDescriptor, Object> allFields = myMsg.getAllFields();
how can I get the value of field "fieldXyz"
?
我怎样才能得到字段的值"fieldXyz"
?
I know that I can use myMsg.getFieldXyz()
, but this is not usable in a systematic way.
我知道我可以使用myMsg.getFieldXyz()
,但这不能以系统的方式使用。
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" :-)
如果无法通过名称访问字段值,我想知道此选择背后的基本原理是什么。我可能仍然需要了解 protobuf 的“哲学”:-)
回答by Wilson
I am not sure you are looking for Descriptors#findFieldByName(name)
. You can try with followings:
我不确定您正在寻找Descriptors#findFieldByName(name)
. 您可以尝试以下操作:
FieldDescriptor fieldDescriptor = message.getDescriptorForType().findFieldByName("fieldXyz");
Object value = message.getField(fieldDescriptor);
回答by user5071787
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)
我知道这是为 java 标记的,但是如果有人正在寻找一种在 c++ 中获取值的方法:(假设:field = FieldDescriptor* 其中包含一个 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!
我花了一段时间才得到这个,但没有找到任何 stackoverflow 引用,因此添加了它。希望能帮助到你。谢谢!