Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@NotNull constraint for primitives, why?

Just encountered a bug, where the issue was that i had:

@Column(name = "ACTIVE")
@NotNull
private boolean active;

In my code I had forgot to set the value but it still "worked" as the default of boolean is false. I have now changed it to Boolean so that it fails the validation if it is not actively set.

Why am I allowed to have @NotNull constraints to things that can obviously not be null? Is it refactoring reasons, so if i change to Boolean as i have done now, i still keep the intended constraint?

Are there any good ideas catch these issues (except more tests for just this purpose)? Or should i keep away from using primitives?

like image 862
Viktor Mellgren Avatar asked Oct 18 '22 23:10

Viktor Mellgren


1 Answers

As javadoc says The annotated element must not be null. Accepts any type.

It can be any type it just checks whether the variable is not null or not, it has nothing to do with whether it accepts null or not.

As mentioned it is applicable for METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER.

@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
like image 153
Prasanna Kumar H A Avatar answered Oct 29 '22 22:10

Prasanna Kumar H A