Protobuf、MapStruct 和空值

Protobuf, MapStruct and null values

给定这个原型

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

这个javaclass:

public class MyFoo {
    String bar;
}

还有这个 Mapper(使用 Mapstruct):

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

当我有一个带有空栏的 MyFoo 实例并尝试将其映射到原型时,我得到一个 NullPointerException。

这是因为 Mapper 的自动生成代码调用了原型的自动生成方法,如下所示:

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

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

有什么办法可以避免这个问题吗? (这不涉及在映射之前清理 MyFoo 实例,使其没有空值)

您需要使用不同的 NullValueCheckStrategy

例如

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

这将始终在调用 setBar

之前执行 null 检查

查看 Controlling checking result for null properties in bean mapping 了解更多信息。