我正在编写一个通用的proto 2 bson文档转换器,并使用描述符映射值。我很难在java protobuf api中找到正确的方法来告诉我是否设置了oneof。
到目前为止,我拥有的是:
} else if (descriptor.getContainingOneof() != null) {
final OneofDescriptor containingOneof = descriptor.getContainingOneof();
for (FieldDescriptor oneOfField : containingOneof.getFields()){
//how to check if the oneof is set and how to find which field in the oneof has the value?
}
我在玩这个,但isInitialized返回true,即使其中一个没有设置。
if (message.hasField(descriptor)) {
final boolean initialized = containingOneof.getOptions().isInitialized();
for (var oneOfItem : containingOneof.getFields()) {
var field = message.getField(oneOfItem);
if(field != null) {
//the field
}
}
}
我怀疑您想要message.getOneofFieldDescriptor(containingOneof)
。来自文档:
如果设置了的给定值,则获取FieldDescriptor。如果未设置字段,则返回null。
请注意,您的isInitialized()
调用只是检查与其中一个相关联的OneofOptions
消息是否已初始化,它与message
无关。