使用反射 API 在 Proto 中填充地图字段 [英] Filling up a map field in Proto using reflection API

查看:110
本文介绍了使用反射 API 在 Proto 中填充地图字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个模块,该模块将获取 Message.Builder 和从字段名称到值的映射,并将用值填充构建器.

I am trying to write a module that will get a Message.Builder and a Map from field name to value and will fill the Builder with the values.

一切正常,直到我遇到地图字段(使用 Proto3).

All works well until I encounter a map field ( using Proto3 ).

我知道我可以执行的特定消息的字段:

I get that for a specific message whose fields I know I can do:

builder.b.putAll<MapeFieldName>( map ),

但是我如何使用 Proto 反射 API 来实现相同的目的.

But how do I use the Proto reflection API to achieve the same.

MapEntry doc说:在反射 API 中,地图字段将被视为重复的消息字段,每个地图条目都作为消息访问."但我不太明白这是什么意思.

The MapEntry doc says: "In reflection API, map fields will be treated as repeated message fields and each map entry is accessed as a message." But I don't quite get what that means.

推荐答案

我在这上面浪费了一些时间,认为其他人可能会觉得它有用:

I have wasted some time on this and thought someone else might find it useful:

在地图字段上使用 proto 反射 API 时,您确实将地图字段视为 com.google.protobuf.MapEntry 的重复字段:

When using the proto reflection API on map fields, you indeed treat the map field as a repeated field of com.google.protobuf.MapEntry:

FieldDescriptor mapFieldDescriptor = protoDescriptor.findFieldByName( map_field_name );
MapEntry.Builder entryBuilder = ( MapEntry.Builder ) topProtoBuilder.newBuilderForField( mapFieldDescriptor );

然后对于我地图中的每个条目:

then for each entry in my map:

entryBuilder.setKey( e.getKey() );
entryBuilder.setValue( e.getValue() );
underlyingProtoBuilder.addRepeatedField( mapFieldDescriptor , entryBuilder.build() );

唯一仍然困扰我的是 MapEntry 文档说:当我必须明确使用 MapEntry.Builder 时,用户不应使用此类".

The only thing that still bothers me is the MapEntry doc saying: "Users shouldn't use this class" when I had to explicitly use the MapEntry.Builder.

我也不确定为什么 protobuf 不让你简单地 builder.setField( mapFieldDescriptor , a java Map ) 看起来更干净.

Also I am not sure why protobuf doesn't let you simply builder.setField( mapFieldDescriptor , a java Map ) which seems much cleaner.

这篇关于使用反射 API 在 Proto 中填充地图字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆