Find the Package of an Object in Java

Java 8Object Oriented ProgrammingProgramming

The package for an object of a class can be obtained using the 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.ArrayList;
import java.util.LinkedList;
import java.util.HashSet;
public class Main {
   public static void main(String[] args) {
      System.out.println("The package is: " + new ArrayList().getClass().getPackage().getName());
      System.out.println("The package is: " + new LinkedList().getClass().getPackage().getName());
      System.out.println("The package is: " + new HashSet().getClass().getPackage().getName());
      System.out.println("The package is: " + "This is a string".getClass().getPackage().getName());
      System.out.println("The package is: " + new Double(1).getClass().getPackage().getName());
      System.out.println("The package is: " + new Integer(1).getClass().getPackage().getName());
   }
}

Output

The package is: java.util
The package is: java.util
The package is: java.util
The package is: java.lang
The package is: java.lang
The package is: java.lang

Now let us understand the above program.

The package is obtained and printed by using getClass().getPackage().getName(). A code snippet which demonstrates this is as follows −

System.out.println("The package is: " + new ArrayList().getClass().getPackage().getName());
System.out.println("The package is: " + new LinkedList().getClass().getPackage().getName());
System.out.println("The package is: " + new HashSet().getClass().getPackage().getName());
System.out.println("The package is: " + "This is a string".getClass().getPackage().getName());
System.out.println("The package is: " + new Double(1).getClass().getPackage().getName());
System.out.println("The package is: " + new Integer(1).getClass().getPackage().getName());
raja
Published on 09-Jan-2019 11:39:31
Advertisements