【问题标题】:Protobuf, MapStruct and null valuesProtobuf、MapStruct 和空值
【发布时间】:2020-11-07 07:02:42
【问题描述】:

鉴于这个原型

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

这个java类:

public class MyFoo {
    String bar;
}

还有这个 Mapper(使用 Mapstruct):

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

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

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

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

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

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

【问题讨论】:

    标签: java protocol-buffers mapstruct


    【解决方案1】:

    您需要使用不同的NullValueCheckStrategy

    例如

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

    这将始终在调用 setBar 之前进行 null 检查

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2022-12-13
      相关资源
      最近更新 更多