Java Get Abbreviated Name of a Class 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 abbreviated name of a Java class.

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 Abbreviated Name of a Class in Java

Apache Commons Lang library provides the method ClassUtils.getAbbreviatedName() to get the abbreviated name of a Class.

The below example code to get the abbreviated name from a given Class object.

GetAbbreviatedNameOfClass.java

import org.apache.commons.lang3.ClassUtils;

import java.io.FileOutputStream;
import java.math.BigDecimal;

public class GetAbbreviatedNameOfClass {
    public static void main(String... args) {
        String result1 = ClassUtils.getAbbreviatedName(ClassUtils.class, 3);
        String result2 = ClassUtils.getAbbreviatedName(BigDecimal.class, 4);
        String result3 = ClassUtils.getAbbreviatedName(FileOutputStream.class, 5);

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}
The output is:
o.a.c.l.ClassUtils
j.m.BigDecimal
j.i.FileOutputStream

The below example code to get the abbreviated name from a given String object of full class name.

GetAbbreviatedNameOfClassName.java

import org.apache.commons.lang3.ClassUtils;

public class GetAbbreviatedNameOfClassName {
    public static void main(String... args) {
        String result1 = ClassUtils.getAbbreviatedName("org.apache.commons.lang3.ClassUtils", 3);
        String result2 = ClassUtils.getAbbreviatedName("java.util.Date", 4);
        String result3 = ClassUtils.getAbbreviatedName("java.io.FileOutputStream", 5);

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}
The output is:
o.a.c.l.ClassUtils
j.u.Date
j.i.FileOutputStream

Happy Coding 😊