Using NotNull Annotation in method argument
@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:
- Calling methods that can return null.
- Dereferencing variables (fields, local variables, parameters) that can be null.
The @NotNull
Annotation is, actually, an explicit contract declaring the following:
- A method should not return null.
- A variable (like fields, local variables, and parameters)
cannotshould not hold null value.
For example, instead of writing:
/**
* @param aX should not be null
*/
public void setX(final Object aX ) {
// some code
}
You can use:
public void setX(@NotNull final Object aX ) {
// some code
}
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 any ConstraintValidator
type reference.
For more info see:
- Bean validation
- NotNull.java
- Constraint.java
- ConstraintValidator.java
As mentioned above @NotNull
does nothing on its own. A good way of using @NotNull
would be using it with Objects.requireNonNull
public class Foo {
private final Bar bar;
public Foo(@NotNull Bar bar) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
}
}