What is the difference between following two code snippets.
public Integer getId(@Nonnull SomeObject obj){
// do some stuff
return id;
}
public Integer getId(SomeObject obj){
Objects.requireNonNull(SomeObject, "SomeObject is null");
// do some stuff
return id;
}
What are the significant differences between them. And what is the correct way to do the null-check in these situations.
requireNonNull(T obj, String message) Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
@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.
The nonNull method is a static method of the Objects class in Java that checks whether the input object reference supplied to it is non-null or not. If the passed object is non-null, then the method returns true. If the passed object is null , then the method returns false.
The two are complementary: @Nonnull
annotation documents the fact that obj
must be non-null, while Objects.requireNonNull
call ensures that obj
is non-null at run-time.
You should combine the two, like this:
public Integer getId(@Nonnull SomeObject obj){
Objects.requireNonNull(SomeObject, "SomeObject is null");
// do some stuff
return id;
}
Relevant documentation on @Nonnull
can be found here:
Optional Type Annotations are not a substitute for runtime validation
Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification.
Your code should still perform runtime validation.
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