2

I am trying to map a source DTO to a protocol buffer object. However, the names of the fields in the source DTO do not match the names in the protocol buffer object, so I need to add custom mappings. I have seen two ways to do this, but both ways are problematic. The issue all stems from the builders in java protocol buffers being Final, so I always get "Cannot map final type" issues when trying to add my custom mappings. The effect of this is that it is seemingly impossible to add custom mappings for anything whose destination is a protobuf object.

Because ModelMapper has gone to the trouble of creating an entire library for Protobuf, I assume that there must be some workaround here, but I am unable to find it.

The value in question needs to be mapped from a Long to an Int64Value.

Solutions I have tried:

mapper.registerModule(new ProtobufModule());
mapper.typeMap(SourceDTO.class, Target.Builder.class)
    .addMappings(map -> map.map(src -> src.getField(), (dest, val) -> dest.setTargetField(Int64Value.newBuilder().setValue((Long) value).build())));

That solution fails due to Cannot map final type com.package.Target$Builder.

mapper.registerModule(new ProtobufModule());
mapper.typeMap(SourceDTO.class, Target.Builder.class)
            .addMappings(new PropertyMap<>() {
              @Override
              protected void configure() {
                map().setTargetField(Int64Value.newBuilder().setTargetValue(source.getField()).build());
              }
            });

That solution fails due to Cannot map final type com.google.protobuf.Int64Value$Builder.

I have seen solutions reccomending that I use using(IntConverters.LONG_VALUE_TO_LONG) to get around the issue of Int64Value$Builder being final, but those solutions require that I use method references to get around type issues, and I cannot make a method reference to Target.Builder::setTargetValue because that is an ambiguous method reference as that method is overloaded. (one with an Int64Value param and one with a Builder param).

To me it seems that this final type restriction is making it impossible to map to a target Protocol Buffer. Has anyone wrangled with this before and found a solution?

Alex A
  • 521
  • 1
  • 4
  • 16

0 Answers0