Get Canonical Name for a class in Java

Java 8Object Oriented ProgrammingProgramming

The canonical name of a class can be obtained using the java.lang.Class.getCanonicalName() method. This method returns the canonical name of the underlying class and returns null if there is no canonical name for the underlying class.

A program that demonstrates the getCanonicalName() method to obtain the canonical name is given as follows −

Example

 Live Demo

package Test;
import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      Demo obj = new Demo();
      Class c = obj.getClass();
      System.out.println("The canonical name of the underlying Class is: " + c.getCanonicalName());
   }
}

Output

The canonical name of the underlying Class is: Test.Demo

Now let us understand the above program.

In the main() method, an object obj of class Demo is created. Then the getClass() method is used to get the runtime class of object obj which is stored in c. Finally the getCanonicalName() method is used to return the canonical name of the underlying class which is class Demo. A code snippet which demonstrates this is as follows −

Demo obj = new Demo();
Class c = obj.getClass();
System.out.println("The canonical name of the underlying Class is: " + c.getCanonicalName());
raja
Published on 09-Jan-2019 13:15:13
Advertisements