Gson.fromJson 即使标记为@NonNull,如果某些字段未给出也不会失败

Gson.fromJson not failing if some fields are not given even though marked as @NonNull

我有一个 POJO 定义如下:

@Value
public class Abc {

    @NonNull
    private final String id;

    @NonNull
    private final Integer id2;

    @NonNull
    private final List<String> data;

    @NonNull
    private final String otherData;
}

我做的时候,

GSON.fromJson(str, Abc.class);

str 为:

{
"id": "dsada",
"id2": 12,
"data": ["dsadsa"]
}

在此,没有其他数据字段。即使那样,GSON.fromJson 也没有失败。为什么会这样?那么,将字段标记为@NonNull 有什么意义吗?

Altgough 与 lombok @Value 你得到一个 allArgs 构造函数,Gson 不会使用它。请注意,lombok 将为您生成 allArg 构造函数,因此不会有 noArg 构造函数 - 但这对 Gson 来说不是问题(从 Gson 2.3.1 开始 - 检查 this SO question)。

@NonNull 注释将使 lombok 在构造函数内部生成空检查,但不会调用此构造函数。这就是为什么 Gson 会毫无问题地读取您的 Json。