Java.lang Package Classes

Java Class - getCanonicalName() Method



The java.lang.Class.getCanonicalName() method returns the canonical name of the underlying class as defined by the Java Language Specification. Returns null if the underlying class does not have a canonical name (i.e., if it is a local or anonymous class or an array whose component type does not have a canonical name).

Syntax

public String getCanonicalName()

Parameters

No parameter is required.

Return Value

Returns the canonical name of the underlying class if it exists, and null otherwise.

Exception

NA.

Example:

The example below shows the usage of java.lang.Class.getCanonicalName() method.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    MyClass x = new MyClass();
    Class cls = x.getClass();

    //print the CanonicalName of the class
    String name = cls.getCanonicalName();
    System.out.println("CanonicalName of class = " + name);
  }
}

The output of the above code will be:

CanonicalName of class = MyClass

❮ Java.lang - Class

5