Java Get Name of Class in Null-safe using Apache Commons Lang

Tags: ClassUtils Apache Commons Apache Commons Lang Class

This Java tutorial shows you how to use the ClassUtils class of Apache Commons Lang library to get the name of a Java class in a null-safe way.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to get name of a class using ClassUtils utility class

The Apache Commons Lang library provides the method ClassUtils.getName() to get the name of a class in a null-safe way.

The following example code to get the class name from a given Class object.

GetNameOfClass.java

import org.apache.commons.lang3.ClassUtils;

import java.util.Date;

public class GetNameOfClass {
    public static void main(String... args) {
        String result1 = ClassUtils.getName(ClassUtils.class);
        String result2 = ClassUtils.getName(Date.class);

        System.out.println(result1);
        System.out.println(result2);
    }
}
The output is:
org.apache.commons.lang3.ClassUtils
java.util.Date

The following example code to get the class name from a given Java object.

GetNameOfObject.java

import org.apache.commons.lang3.ClassUtils;

import java.math.BigInteger;
import java.util.Date;

public class GetNameOfObject {
    public static void main(String... args) {
        BigInteger bigIntegerValue = new BigInteger("1234");
        Date date = new Date();

        String result1 = ClassUtils.getName(bigIntegerValue, "");
        String result2 = ClassUtils.getName(date, "");

        System.out.println(result1);
        System.out.println(result2);
    }
}
The output is:
java.math.BigInteger
java.util.Date

Happy Coding 😊