How do I get package name of a class?

To get the package name of a class we can use the getClass().getPackage() method.

package org.kodejava.example.lang;

import java.util.Date;

public class ObtainingPackageName {
    public static void main(String[] args) {
        // Create an instance of Date class, and then obtain the class package
        // name.
        Date date = new Date();
        Package pack = date.getClass().getPackage();
        String packageName = pack.getName();
        System.out.println("Package Name = " + packageName);

        // Create an instance of our class and again get its package name
        ObtainingPackageName o = new ObtainingPackageName();
        packageName = o.getClass().getPackage().getName();
        System.out.println("Package Name = " + packageName);

Our code printed the following output:

Package Name = java.util
Package Name = org.kodejava.example.lang

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.