@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.
Hi, when using the @NotNull annotation, IntelliJ will generate bytecode to throw an IllegalArgumentException when a null is passed/returned.
@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:
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:
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");
}
}
To make @NonNull
active you need Lombok:
https://projectlombok.org/features/NonNull
import lombok.NonNull;
Follow: Which @NotNull Java annotation should I use?
SO @NotNull just is a tag...If you want to validate it, then you must use something like hibernate validator jsr 303
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<List<Searching>> violations = validator.validate(searchingList);
If you are using Spring, you can force validation by annotating the class with @Validated
:
import org.springframework.validation.annotation.Validated;
More info available here: Javax @NotNull annotation usage
You could also use @NonNull
from projectlombok
(lombok.NonNull)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With