@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