Java Get Package Name of a Class using Apache Commons Lang

Tags: ClassUtils Apache Commons Apache Commons Lang Class Package

This Java tutorial shows you how to get the package name of a Java class using the ClassUtils utility 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 Package Name of a Java Class

Apache Commons Lang library provides the method ClassUtils.getPackageName() to get the package name of a given Java class.

The following example Java code to get package name from a given Class object

GetPackageNameOfClass.java

import org.apache.commons.lang3.ClassUtils;

import java.math.BigDecimal;
import java.util.Date;

public class GetPackageNameOfClass {
    public static void main(String... args) {
        String result1 = ClassUtils.getPackageName(ClassUtils.class);
        String result2 = ClassUtils.getPackageName(Date.class);
        String result3 = ClassUtils.getPackageName(BigDecimal.class);

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

You can also get the package name from a given class name String as below example code.

GetPackageNameOfClassName.java

import org.apache.commons.lang3.ClassUtils;

public class GetPackageNameOfClassName {
    public static void main(String... args) {
        String result1 = ClassUtils.getPackageName("org.apache.commons.lang3.ClassUtils");
        String result2 = ClassUtils.getPackageName("java.util.Date");

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

Or from a given Java object as below Java program.

GetPackageNameOfObject.java

import org.apache.commons.lang3.ClassUtils;

import java.math.BigDecimal;
import java.util.Date;

public class GetPackageNameOfObject {
    public static void main(String... args) {
        BigDecimal bigDecimalValue = new BigDecimal("10.20");
        Date date = new Date();

        String result1 = ClassUtils.getPackageName(bigDecimalValue, "");
        String result2 = ClassUtils.getPackageName(date, "");

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

Happy Coding 😊