How to get package name of a class using reflection in java

This example shows you how to get the package name of a class using reflection in java.

You need to get the Package object by getting the class object, than you can call the getName() method in order to get the package of that class.

Below is the example of code which obtain the class package name.

package com.java.connect.lang;
 
import java.util.Date;
 
//How to get package name of a class in java
public class GettingClassPackageNameExample {
    public static void main(String[] args) {
        // Create an instance of String class,
        // and then get the class package name.
        String string = new String();
        Package pack = string.getClass().getPackage();
        String packageName = pack.getName();
        System.out.println("The String class package Name : " + packageName);
 
        // Create an instance of Date class,
        // and then obtain the class package name.
        Date date = new Date();
        pack = date.getClass().getPackage();
        packageName = pack.getName();
        System.out.println("The Date class package Name : " + packageName);
 
        // Create an instance of this class,
        // and get its package name
        GettingClassPackageNameExample o = new GettingClassPackageNameExample();
        packageName = o.getClass().getPackage().getName();
        System.out.println("This Class package Name : " + packageName);
    }
}

The output of the above example will be as:

The String class package Name : java.lang
The Date class package Name : java.util
This Class package Name : com.java.connect.lang