Over a million developers have joined DZone.

Checking for Null Values in Java with Objects.requiresNonNull()

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Checking method/constructor parameters for null values is a common task problem in Java. To assist you with this, various Java libraries provide validation utilities (see Guava PreconditionsCommons LangValidate or Spring's Assert documentation).
However, if you only want to validate for non null values you can use the static requiresNonNull()method of java.util.Objects. This is a little utility introduced by Java 7 that appears to be rarely known.

With Objects.requiresNonNull() the following piece of code

public void foo(SomeClass obj) {
	if (obj == null) {
		throw new NullPointerException("obj must not be null");
	// work with obj

can be replaced with:

import java.util.Objects;

public void foo(SomeClass obj) {
	Objects.requireNonNull(obj, "obj must not be null");
	// work with obj

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.


Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}