Get / Find Package Name Of Java Class

In this tutorial, we are find / get the package name of a Java class by providing the class name using java API.

Package packs = str.getClass().getPackage();

On above code we are using object.getClass().getPackage() method for getting the package name.

Find Package Name Of Java Class

package com.examples;

public class FindPackageName {
   
   
//Find package name of a class
   
public static void main(String[] args) {
       
       
// Get package name of String class
       
String str = new String();
        Package packs = str.getClass
().getPackage();
        String packageName = packs.getName
();
        System.out.println
("Package Name = " + packageName);

       
// Find current class name package
       
FindPackageName o = new FindPackageName();
        packageName = o.getClass
().getPackage().getName();
        System.out.println
("Package Name = " + packageName);
   
}
}
Output
Package Name = java.lang
Package Name = com.examples

Find Package Name Of Current Java Class

If you need to append class name with package name, then you need to use this.getClass().getCanonicalName() by replacing this.getClass().getPackage()

package com.examples;

public class FindPackageNameOfCurrentClass {

   
// Find current package name of a class
   
public static void main(String[] args) {
       
FindPackageNameOfCurrentClass fpnc = new FindPackageNameOfCurrentClass();
        System.out.println
("current package name ="+fpnc.getCurrentPackage().getName());
   
}

   
private Package getCurrentPackage() {
       
return this.getClass().getPackage();
   
}
}
Output
current package = name com.examples

 






Your email address will not be published. Required fields are marked *