Java Get Short Class Name of a Class using Apache Commons Lang
Tags: ClassUtils Apache Commons Apache Commons Lang Class
This Java tutorial shows you how to get the short class name of a Java class which returns the class name without package name using the ClassUtils class of Apache Commons Lang library.
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 Short Class Name in Java using ClassUtils class
The Apache Commons Lang library provides the method ClassUtils.getShortClassName() to get the short class name minus the package name for a given class.
The code example below to get the short class name from a given Class object.
GetShortClassNameOfClass.java
import org.apache.commons.lang3.ClassUtils;
import java.util.Date;
public class GetShortClassNameOfClass {
public static void main(String... args) {
String result1 = ClassUtils.getShortClassName(ClassUtils.class);
String result2 = ClassUtils.getShortClassName(Date.class);
System.out.println(result1);
System.out.println(result2);
}
}
ClassUtils
Date
The code example below to get the short class name from a full class name in String.
GetShortClassNameOfClassName.java
import org.apache.commons.lang3.ClassUtils;
public class GetShortClassNameOfClassName {
public static void main(String... args) {
String result1 = ClassUtils.getShortClassName("org.apache.commons.lang3.ClassUtils");
String result2 = ClassUtils.getShortClassName("java.util.Date");
System.out.println(result1);
System.out.println(result2);
}
}
ClassUtils
Date
The code example below to get the short class name from a given object value.
GetShortClassNameOfObject.java
import org.apache.commons.lang3.ClassUtils;
import java.util.Date;
public class GetShortClassNameOfObject {
public static void main(String... args) {
Double doubleValue = new Double(10.20);
Date date = new Date();
String result1 = ClassUtils.getShortClassName(doubleValue, "");
String result2 = ClassUtils.getShortClassName(date, "");
System.out.println(result1);
System.out.println(result2);
}
}
Double
Date
Happy Coding 😊