I'm writing a generic proto 2 bson document converter and using the descriptors to map the values. I'm having a time finding the correct method within the java protobuf api to tell me if a oneof is set.
What I have so far is:
} 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?
}
I am toying with this but isInitialized returns true even if the oneof isn't set.
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
}
}
}
I suspect you want message.getOneofFieldDescriptor(containingOneof)
. From the docs:
Obtains the FieldDescriptor if the given oneof is set. Returns null if no field is set.
Note that your isInitialized()
call is just checking whether the OneofOptions
message associated with the oneof is initialized - it has nothing to do with message
.