requireNonEmpty() is a ObjectUtils class that is used to check whether a specified object reference is not null or not empty according to the isEmpty() method. If the specified object reference is either null or empty, the method throws an exception with the specified message.
ObjectUtilsThe definition of ObjectUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the ObjectUtils class as follows:
import org.apache.commons.lang3.ObjectUtils;
public static <T> T requireNonEmpty(T obj, String message)
obj: The object to check of type T.message: The exception message if the object is null or empty.This method returns the input object if it is not null.
import org.apache.commons.lang3.ObjectUtils;public class Main{public static void main(String[] args) {// Example 1String object = "hello";System.out.printf("ObjectUtils.requireNonEmpty(%s) = %s", object, ObjectUtils.requireNonEmpty(object));System.out.println();// Example 2object = "";String message = "Object must not be empty/null";System.out.printf("ObjectUtils.requireNonEmpty(%s) = %s", object, ObjectUtils.requireNonEmpty(object, message));System.out.println();}}
The output of the code will be as follows:
ObjectUtils.requireNonEmpty(hello) = hello
Exception in thread "main" java.lang.IllegalArgumentException: Object must not be empty/null
at org.apache.commons.lang3.ObjectUtils.requireNonEmpty(ObjectUtils.java:1241)
at Main.main(Main.java:12)
object = "hello"The method returns hello because the object is neither empty nor null.
object = ""The method throws an IllegalArgumentException with the exception message, as Object must not be empty/null.