Lombok的@NonNull注释是否允许默认构造函数提供空值? [英] Is @NonNull annotation of Lombok allows the default constructor to give null values?

查看:1435
本文介绍了Lombok的@NonNull注释是否允许默认构造函数提供空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上课说C

class C {
  @NonNull
  private String str;
  //getters
  //setters
}

现在我做了这样的事情:

Now I did something like this :

C ob = new C();
System.out.println(ob.getStr());

令我惊讶的是,它打印为空.

To my surprise it printed null.

但是,当我这样做时,它给了Null指针例外:

However, it gave Null pointer exception when I did:

ob.setStr(null)

@NonNull是否不保留默认构造函数?请解释.

Does @NonNull does not hold on default constructors? Please explain.

推荐答案

@NonNull是否不保留默认构造函数?

Does @NonNull does not hold on default constructors?

的确是,不是,我也不知道怎么可能.当编译器提供默认构造函数时,会在编译过程中的 注释处理之后发生.

Indeed no, it doesn't, and I don't see how it could. When a default constructor is provided by the compiler, that happens during compilation, after annotation processing.

此外,龙目岛自己的文档可以说该注释与字段一起使用:

Moreover, Lombok's own docs have this to say of that annotation's use with fields:

Lombok始终将字段上任何名为@NonNull的注释视为 如果lombok生成整个方法,则生成空检查 的信号 或您的构造函数 ,例如@Data.现在,使用 龙目岛自己在参数上的@lombok.NonNull导致插入 您自己的 方法中的null-check语句,或者 构造函数.

Lombok has always treated any annotation named @NonNull on a field as a signal to generate a null-check if lombok generates an entire method or constructor for you, via for example @Data. Now, however, using lombok's own @lombok.NonNull on a parameter results in the insertion of just the null-check statement inside your own method or constructor.

也就是说,注释仅对您自己的构造函数和方法(即,源代码中存在的那些)和Lombok为您生成的那些有效.编译器提供的默认构造函数都不是.

That is, the annotation has effect only on your own constructors and methods (i.e. those present in your source code) and those Lombok generates for you. A default constructor provided by the compiler is neither.

这篇关于Lombok的@NonNull注释是否允许默认构造函数提供空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆