mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Wednesday, 1 October, 2014

Checking for null values in Java with Objects.requiresNonNull()

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 Preconditions, Commons Lang Validate 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
}

Leave a reply