简体   繁体   中英

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

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.

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 (ie those present in your source code) and those Lombok generates for you. A default constructor provided by the compiler is neither.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM