Is @NonNull annotation of Lombok allows the default constructor to give null values?

被刻印的时光 ゝ 提交于 2020-01-13 05:37:28

问题


I have a class say 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.


回答1:


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 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.

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.




回答2:


Please read the documentation...

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.

You are using the default constructor, so Lombok is not generating a constructor for you, therefore there is no null check.


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.



来源:https://stackoverflow.com/questions/44292453/is-nonnull-annotation-of-lombok-allows-the-default-constructor-to-give-null-val

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!