To return the package name with the class name in Java I have always used the getName()
. I noticed that apparently the method getCanonicalName()
returns the same thing.
See just an example customizing the method toString()
:
@Override
public String toString() {
return this.getClass().getName();
}
Isso would apparently be equivalent to:
@Override
public String toString() {
return this.getClass().getCanonicalName();
}
What is the actual difference between the getCanonicalName()
and methods getName()
?
getName() Returns the name of the entity (class, interface, array, primitive type, or void) represented by this class object, as a string. This name is used to dynamically load the class using Class.forName()
getCanonicalName() Returns the canonical name of the underlying class defined by the Java language specification. Returns null if the underlying class does not have a canonical name (that is, if it is a local or anonymous class or an array whose component type does not have a canonical name). This is the name that would be used in an import statement and would uniquely identify the class. It can be useful during logging operations.
Gets as output:
I think it is important to also add:
getSimpleName() Returns the "simple name" of the underlying class as indicated in the source code. Returns an empty string if the underlying class is anonymous. Loosely identifies the class, may be useful during logging operations, but is not guaranteed to be unique.
Gets as output:
An important difference is that if you use an anonymous class you can get a null value when trying to get the class name using
getCanonicalName()
getName()
getCanonicalName()
getSimpleName()
I will explain it to you with a test:
Result:
The result of looking at this is:
The name is the name you would use to dynamically load the class with, for example, a call to
Class.forName
withClassLoader
default.The canonical name is the name that would be used in an import statement and would uniquely identify the class. It can be useful during
toString
log operations.