Java Class getCanonicalName() Method



Description

The Java Class getCanonicalName() method returns the canonical name of the underlying class as defined by the Java Language Specification. It returns null if the class does not have a canonical name.

Declaration

Following is the declaration for java.lang.Class.getCanonicalName() method

public String getCanonicalName()

Parameters

NA

Return Value

This method returns the canonical name of the underlying class if it exists, and null otherwise.

Exception

NA

Getting Canonical Name of a Class Example

The following example shows the usage of java.lang.Class.getCanonicalName() method. In this program, we've created an instance of ClassDemo and then using getClass() method, the class of the instance is retrieved. Using getCanonicalName(), we've retrieved the canonical name and result is printed.

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      ClassDemo c = new ClassDemo();
      Class cls = c.getClass();

      // returns the canonical name of the underlying class if it exists
      System.out.println("Class = " + cls.getCanonicalName()); 
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Class = com.tutorialspoint.ClassDemo

Getting Canonical Name of Thread Class Example

The following example shows the usage of java.lang.Class.getCanonicalName() method. In this program, using class property, the class of the Thread Class is retrieved. Then Using getCanonicalName(), we've retrieved the canonical name and result is printed.

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      // returns the canonical name of the class
      System.out.println("Class = " + Thread.class.getCanonicalName()); 
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Class = java.lang.Thread

Getting Canonical Name of ArrayList Class Example

The following example shows the usage of java.lang.Class.getCanonicalName() method. In this program, using class property, the class of the ArrayList Class is retrieved. Then Using getCanonicalName(), we've retrieved the canonical name and result is printed.

package com.tutorialspoint;

import java.util.ArrayList;

public class ClassDemo {

   public static void main(String[] args) {

      // returns the canonical name of the class
      System.out.println("Class = " + ArrayList.class.getCanonicalName()); 
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Class = java.util.ArrayList
java_lang_class.htm
Advertisements