CKTIS / Java
Class.getName() — type names in Java
`Class.getName()` returns the name of the represented type. For ordinary classes and interfaces, this is the binary name; arrays use a different notation.
Version: Java SE 21
Syntax
public String getName()Class.getName is a no-argument instance method that returns a String. Use Type.class.getName() when you know the type, or object.getClass().getName() to get the object's actual class rather than the variable's declared type. Calling getClass() on null throws NullPointerException.
For a non-hidden, non-array class or interface, the result is its binary name. For ArrayList, that is java.util.ArrayList: it includes the package but not type arguments such as <String>. A member type uses $ as the separator, as in java.util.Map$Entry. A hidden class or interface instead uses the form N/suffix, where N is the binary name stored in the class file.
An array name starts with one [ per dimension, followed by the element type's encoding. For a reference type with binary name N, that encoding is L + N + ;, so String[] gives [Ljava.lang.String;. The array code for int is I, so int[][] gives [[I. Outside an array, primitive types and void use their keyword spellings, such as int and void.
For Map.Entry, getSimpleName() returns Entry, whereas getCanonicalName() returns java.util.Map.Entry. If there is no canonical name, as with an anonymous class, getCanonicalName() returns null. The result of getName() is neither a hash nor a unique type identifier: distinct Class objects can share a name when they come from different class loaders.
Examples
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<String> items = new ArrayList<>();
System.out.println(List.class.getName());
System.out.println(items.getClass().getName());
System.out.println(Map.Entry.class.getName());
System.out.println(String[].class.getName());
System.out.println(int[][].class.getName());
System.out.println(int.class.getName());
System.out.println(void.class.getName());
}
}
Result
java.util.List java.util.ArrayList java.util.Map$Entry [Ljava.lang.String; [[I int void
The first line names the `List` interface. The second names the actual implementation, `java.util.ArrayList`, even though the variable is declared as `List<String>`.
Related lessons
- Java · Lesson 5 · Advanced · Version: 2
- Java · Lesson 13 · Advanced · Version: 2
- Java · Lesson 8 · Intermediate · Version: 2