Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

lombok

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.

like image 752
Rajat Mishra Avatar asked Feb 04 '23 08:02

Rajat Mishra


1 Answers

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.

like image 171
John Bollinger Avatar answered May 10 '23 23:05

John Bollinger