Get the unqualified name of a class in Java


A qualified class name in Java contains the package that the class originated from. In contrast to this, the unqualified class name contains only the class name without any package information. 

A program that gets the unqualified name of a class is given as follows:

Example

 Live Demo

public class Demo {
   public static void main(String[] argv) throws Exception {
      Class c = java.util.ArrayList.class;
      String className = c.getName();
      System.out.println("The qualified class name is: " + className);
      if (className.lastIndexOf('.') < 0) {
         className = className.substring(className.lastIndexOf('.') + 1);
         className = className.replace('$', '.');
      }
      System.out.println("The unqualified class name is: " + className);
   }
}

Output

The qualified class name is: java.util.ArrayList The unqualified class name is: ArrayList

Now let us understand the above program.

First the qualified class name is displayed using the getName() method. A code snippet which demonstrates this is as follows −

Class c = java.util.ArrayList.class;
String className = c.getName();
System.out.println("The qualified class name is: " + className);

The unqualified class name is obtained using the substring() method that provides the substring of the className from the last index of ‘.’ Then the unqualified class name is displayed. A code snippet which demonstrates this is as follows −

if (className.lastIndexOf('.') < 0) {
   className = className.substring(className.lastIndexOf('.') + 1);
   className = className.replace('$', '.');
}
System.out.println("The unqualified class name is: " + className);

Updated on: 25-Jun-2020

378 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements