What is the difference between Java's Class.getName()
and Class.getCanonicalName()
?
Canonical name of a Java class is the name of the class along with the package. For example, the canonical name of the class File is java. io. File. You can also get the canonical name of a particular class using Java method.
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.
The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.
A canonical name (CNAME) is a type of Domain Name System (DNS) database record that indicates that a domain name is the nickname or alias for another domain name. Also referred to as the "true name," the CNAME is especially important when multiple services run from a single IP address.
Consider the following program:
package org.test.stackoverflow;
public class CanonicalName {
public static void main(String[] args) {
CanonicalName cn = new CanonicalName();
cn.printClassNames();
}
private Anonymous anony;
private MyAnony myAnony;
public CanonicalName() {
anony = new Anonymous() {
public void printInterface() {
System.out.println("Anony Name: " + getClass().getName());
System.out.println("Anony CanonicalName: " + getClass().getCanonicalName());
}
};
myAnony = new MyAnony();
}
public void printClassNames() {
System.out.println("CanonicalName, Name: " + getClass().getName());
System.out.println("CanonicalName, CanonicalName: " + getClass().getCanonicalName());
anony.printInterface();
myAnony.printInterface();
}
private static interface Anonymous {
public void printInterface();
}
private static class MyAnony implements Anonymous {
public void printInterface() {
System.out.println("MyAnony Name: " + getClass().getName());
System.out.println("MyAnony CanonicalName: " + getClass().getCanonicalName());
}
}
}
Output:
CanonicalName, Name: org.test.stackoverflow.CanonicalName
CanonicalName, CanonicalName: org.test.stackoverflow.CanonicalName
Anony Name: org.test.stackoverflow.CanonicalName$1
Anony CanonicalName: null
MyAnony Name: org.test.stackoverflow.CanonicalName$MyAnony
MyAnony CanonicalName: org.test.stackoverflow.CanonicalName.MyAnony
So it seems that for base classes, they return the same thing. For inner classes, getName()
uses the $
naming convention (i.e. what is used for .class files), and getCanonicalName()
returns what you would use if you were trying to instantiate the class. You couldn't do that with a (little-a) anonymous class, so that's why getCanonicalName()
returns null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With