I just started using the @NotNull
annotation with Java 8 and getting some unexpected results.
I have a method like this:
public List<Found> findStuff(@NotNull List<Searching> searchingList) {
... code here ...
}
I wrote a JUnit test passing in the null value for the argument searchingList. I was expecting some type of error to happen but it went through as though the annotation was not there. Is this expected behavior? From what I understood, this was to allow you to skip writing the boilerplate null check code.
An explanation of what exactly @NotNull is supposed to do would be greatly appreciated.
Best Answer
@Nullable
and@NotNull
do nothing on their own. They are supposed to act as Documentation tools.The
@Nullable
Annotation reminds you about the necessity to introduce an NPE check when:The
@NotNull
Annotation is, actually, an explicit contract declaring the following:cannotshould not hold null value.For example, instead of writing:
You can use:
Additionally,
@NotNull
is often checked by ConstraintValidators (eg. in spring and hibernate).The
@NotNull
annotation doesn't do any validation on its own because the annotation definition does not provide anyConstraintValidator
type reference.For more info see: