What is the difference between @Nonnull and Objects.requireNonNull

What is the difference between the following two pieces of code.

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 the two. And what is the correct way to do a null check in these situations.

+7
java
source share
3 answers

These two are complementary: @Nonnull annotations document the fact that obj must not be null, and a call to Objects.requireNonNull ensures that obj not null at runtime.

You must combine the two, for example:

 public Integer getId(@Nonnull SomeObject obj){ Objects.requireNonNull(SomeObject, "SomeObject is null"); // do some stuff return id; } 

The relevant @Nonnull documentation can be found here :

Optional type Annotations do not replace execution verification

Before the annotation type, the main place to describe things like zeros or ranges was in javadoc. With annotations of type, this message is included in the bytecode to check compilation time.

Your code should still perform a validation check.

+10
source share

The difference is that in the first case it is a hint for the compiler and IDE that the argument should not be null, so when you write getId(null) , you get an error message. But someone might pass null at runtime.

As for the second case, this is a kind of defensive programming, when you do not perform quick actions with the precondition that the argument must not be null .

+3
source share

One of them is an annotation that implements JSR-305 , but is intended for static analysis, and not to protect run-time. As far as I remember, JSR-305 is a good idea in principle, and many things actually somehow use it, but it loses a lot of its bark when its usefulness only ever comes in the form of static analysis.

Example: your IDE can use this to alert you to situations in which you are passing something that you should not, but that cannot stop you from passing null to this method when compiling.

Objects.requireNonNull is a enforcement that, no matter how it is passed, will be a reference to a non-zero value. The compiler cannot execute this either, but at runtime, if you get a null value, you will get a NullPointerException when this line of code is executed.

In terms of correctness, using Objects.requireNonNull is a good idea, but it depends on what your responsibility is when starting the application. If you must fail on a zero value, then use this normally, as it will throw an exception at runtime. If you cannot fail at a zero value, it is better to use an if check instead.

+2
source share

All Articles