Protobuf, MapStruct and null values

Viewed 1243

Given this proto

option java_outer_classname = "FooProto";
message Foo {
    string bar = 1;
}

This java class:

public class MyFoo {
    String bar;
}

And this Mapper (using Mapstruct):

@Mapper
public interface FooMapper() {
    FooProto.Foo toProtoFoo(MyFoo myFoo);
}

When I have an instance of MyFoo with a null bar and I try to map it to the proto I get a NullPointerException.

This is because the auto-generated code for the Mapper invokes an auto-generated method for the proto that looks like:

public Builder setBar(java.lang.String value) {
    if (value == null) {
        throw new NullPointerException();
    }

    bar_ = value;
    onChanged();
    return this;
}

Is there any way of avoiding this problem? (that does not involve sanitizing MyFoo instance before mapping so that it has no null values)

1 Answers

You'll need to use a different NullValueCheckStrategy.

e.g.

@Mapper(nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface FooMapper() {
    FooProto.Foo toProtoFoo(MyFoo myFoo);
}

This will always do a null check before invoking setBar

Have a look at Controlling checking result for null properties in bean mapping for more info.

Related