java Lombok 的@NonNull 注释是否允许默认构造函数提供空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44292453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is @NonNull annotation of Lombok allows the default constructor to give null values?
提问by Rajat Mishra
I have a class say C
我有一个班级说 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.
令我惊讶的是它打印为空。
However, it gave Null pointer exception when I did:
但是,当我这样做时,它给出了空指针异常:
ob.setStr(null)
Does @NonNull
does not hold on default constructors? Please explain.
不@NonNull
不上默认构造持有?请解释。
回答by John Bollinger
Does @NonNull does not hold on default constructors?
@NonNull 不保留默认构造函数吗?
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, afterannotation processing.
确实不,它没有,我不明白它怎么可能。当编译器提供默认构造函数时,这会在编译期间,注释处理之后发生。
Moreover, Lombok's own docshave this to say of that annotation's use with fields:
此外,Lombok 自己的文档有关于该注释与字段的使用的说法:
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 ownmethod or constructor.
Lombok 始终将
@NonNull
字段上命名的任何注释视为信号,以生成空检查,如果 lombok 为您生成整个方法或构造函数,例如通过@Data。但是,现在,@lombok.NonNull
在参数上使用 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 为您生成的那些构造函数和方法有效。编译器提供的默认构造函数两者都不是。
回答by Michael
Please read the documentation...
请阅读文档...
Lombok has always treated any annotation named @NonNull on a fieldas a signal to generate a null-check if lombok generates an entire method or constructor for you, via for example @Data.
Lombok 始终将字段上名为 @NonNull 的任何注释视为信号,以生成空检查,如果 lombok 为您生成整个方法或构造函数,例如通过 @Data。
You are using the default constructor, so Lombok is not generating a constructor for you, therefore there is no null check.
您使用的是默认构造函数,因此 Lombok 不会为您生成构造函数,因此没有空检查。
If it did what you were expecting, every default constructed object of your class:
如果它符合您的预期,您的类的每个默认构造对象:
C ob = new C();
would immediately result in a null pointer exception. Not exactly very useful.
将立即导致空指针异常。不是很有用。