Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @Nonnull and Objects.requireNonNull

Tags:

java

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.

like image 441
prime Avatar asked Jan 04 '18 21:01

prime


People also ask

What is Objects requireNonNull?

requireNonNull(T obj, String message) Checks that the specified object reference is not null and throws a customized NullPointerException if it is.

What does @NonNull annotation do?

@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.

How do you use Objects NonNull?

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.


1 Answers

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.

like image 199
Sergey Kalinichenko Avatar answered Oct 03 '22 05:10

Sergey Kalinichenko