Display the package name of a class in Java


The package for a class can be obtained using the java.lang.Class.getPackage() method with the help of the class loader of the class. If there is no package object created by the class loader of the class, then null is returned.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Date;
public class Main {
   public static void main(String[] args) {
      Date d = new Date();
      Package p = d.getClass().getPackage();
      String pName = p.getName();
      System.out.println("The package name is: " + pName);
   }
}

Output

The package name is: java.util

Now let us understand the above program.

The getPackage() method is used to obtain the package for the class. Then getName() method is used to get the name of the package. Then this name is displayed. A code snippet which demonstrates this is as follows −

Date d = new Date();
Package p = d.getClass().getPackage();
String pName = p.getName();
System.out.println("The package name is: " + pName);

Updated on: 25-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements