Getting Class Name Information
You'll learn how to extract different forms of a class's name—simple, canonical, and package—from a Class object.
Different Names for the Same Class
Once you have a Class object (using .class, getClass(), or Class.forName()), you can retrieve its name in several formats. Think of it like addresses: you might refer to a building by its street number, full address, or just the street name—all valid, but serving different purposes.
The Three Name Methods
getName()
Returns the full internal name of the class as the JVM sees it. For regular classes, this is the fully-qualified name with package. For arrays, it uses JVM notation (like [Ljava.lang.String;).
Class<?> stringClass = String.class;
System.out.println(stringClass.getName());
// Output: java.lang.String
getSimpleName()
Returns just the class name without package, as you'd write it in source code. This is human-friendly and great for logging or display purposes.
Class<?> arrayListClass = java.util.ArrayList.class;
System.out.println(arrayListClass.getSimpleName());
// Output: ArrayList
getCanonicalName()
Returns the fully-qualified name in human-readable format. For most classes, this matches getName(), but differs for inner classes (uses . instead of $) and arrays (uses [] syntax).
int[] numbers = {1, 2, 3};
Class<?> arrayClass = numbers.getClass();
System.out.println(arrayClass.getCanonicalName());
// Output: int[]
getPackageName()
Returns just the package portion of the class name, without the class itself.
System.out.println(String.class.getPackageName());
// Output: java.lang
Key Takeaway: Use getSimpleName() for display, getName() for internal processing, getCanonicalName() for readable fully-qualified names, and getPackageName() when you only need package information.