Get full package name for a given class in Java

Description

The following code shows how to get full package name for a given class.

Example


/*  w w  w.jav  a2 s.co m*/
public class Main {
  public static String getPackageName(Class c) {
    String fullyQualifiedName = c.getName();
    int lastDot = fullyQualifiedName.lastIndexOf('.');
    if (lastDot == -1) {
      return "";
    }
    return fullyQualifiedName.substring(0, lastDot);
  }

  public static void main(String[] args) {
    System.out.println(getPackageName(java.awt.Frame.class));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy