Java Get Simple 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 simple 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 simple name of a class using ClassUtils utility class
The Apache Commons Lang library provides the method ClassUtils.getSimpleName() to get the simple name of a class in a null-safe way.
The following example code to get the simple class name from a given Class object.
GetSimpleNameOfClass.java
import org.apache.commons.lang3.ClassUtils;
import java.util.Date;
public class GetSimpleNameOfClass {
public static void main(String... args) {
String result1 = ClassUtils.getSimpleName(ClassUtils.class);
String result2 = ClassUtils.getSimpleName(Date.class);
System.out.println(result1);
System.out.println(result2);
}
}
ClassUtils
Date
The following example code to get the simple class name from a given Java object value.
GetSimpleNameOfObject.java
import org.apache.commons.lang3.ClassUtils;
import java.util.Date;
public class GetSimpleNameOfObject {
public static void main(String... args) {
Long longValue = 1000L;
Date date = new Date();
String result1 = ClassUtils.getSimpleName(longValue);
String result2 = ClassUtils.getSimpleName(date);
System.out.println(result1);
System.out.println(result2);
}
}
Long
Date
Happy Coding 😊