CKTIS / Java
Class.getSimpleName() — the type name without its package
Use `getSimpleName()` for a short type label in a report. For a nested type, the result leaves out both the package and the enclosing type names.
Version: Java SE 21
Syntax
public String getSimpleName()
TypeName.class.getSimpleName()
object.getClass().getSimpleName()Class.getSimpleName is a no-argument instance method of java.lang.Class that returns a String. Use Map.Entry.class.getSimpleName() for a type named in your code, or obj.getClass().getSimpleName() for the object's actual runtime class, rather than the declared type of obj.
For a named source type, the result is its name as written in the declaration, without the package or enclosing type names. For Map.Entry, it is Entry. For that same type, getName() returns the binary name java.util.Map$Entry, while getCanonicalName() returns the canonical name java.util.Map.Entry. A named local class has a simple name but no canonical name, so getCanonicalName() returns null for it.
An array's name has one [] per dimension after the element type's simple name, as in String[][]. An anonymous class has an empty simple name ("", not null), so a one-dimensional array of that class has the simple name []. A synthetic class can have a nonempty name containing characters such as $.
Use the simple name as a readable report label, not as a unique identifier: different types can share it. If your label must not be empty, check isEmpty() and supply fallback text.
Examples
import java.util.Map;
public class Main {
public static void main(String[] args) {
Class<?> type = Map.Entry.class;
System.out.println("Simple: " + type.getSimpleName());
System.out.println("Binary: " + type.getName());
System.out.println("Canonical: " + type.getCanonicalName());
System.out.println("Array: " + String[][].class.getSimpleName());
Object item = new Object() {};
System.out.println("Anonymous: [" + item.getClass().getSimpleName() + "]");
}
}Result
Simple: Entry Binary: java.util.Map$Entry Canonical: java.util.Map.Entry Array: String[][] Anonymous: []
`Map.Entry` shows how the three naming methods differ. On the last line, `[]` is the pair of brackets the program prints around the empty result, not an array name.
Related lessons
- Java · Lesson 30 · Intermediate · Version: 2