I want to merge two complex proto objects protoA and protoB of the same type, where if a field is set in both the objects, the value of protoB should be set in the resulting proto.
I could use the .mergeFrom() function:
protoA.toBuilder().mergeFrom(protoB).build()
but according to the docs, repeated fields will be concatenated.
mergeFrom(Message other): (builder only) merges the contents of other into this message, overwriting singular scalar fields, merging composite fields, and concatenating repeated fields.
I don't want this behaviour. Is there a elegant way to do this than to manually set each repeated fields?
In FieldMaskUtil from protobuf there is an option to merge overriding existing fields.
It has a MergeOptions where you can configure setReplaceRepeatedFields(true); it will merge protoB into protoA taking protoB fields when repeated.
I will write you an example:
FieldMaskUtil.MergeOptions options = 
      new FieldMaskUtil.MergeOptions().setReplaceRepeatedFields(true);
// Now we get all the names of the fields in your proto
List<String> names = YourObjectProto.YourObject.getDescriptor().getFields()
           .stream().map(Descriptors.FieldDescriptor::getName)
           .collect(Collectors.toList());
FieldMaskUtil.merge(FieldMaskUtil.fromStringList(names),
      protoB, protoA.toBuilder(),options);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With