getClass() Method in Java
A variable's declared type and the object it holds can differ: Account a = new SavingsAccount(...). getClass() tells you what the object really is at runtime. It returns a Class object, the JVM's description of that class, from which you can read the name, the parent class and much more. It's final in Object, so every object answers it the same reliable way.
Asking an Object What It Is
public class WhatAmI {
static class Account { }
static class SavingsAccount extends Account { }
public static void main(String[] args) {
Account a = new SavingsAccount();
Class<?> c = a.getClass();
System.out.println(c.getName());
System.out.println(c.getSimpleName());
System.out.println(c.getSuperclass().getSimpleName());
System.out.println(a.getClass() == SavingsAccount.class);
System.out.println(a.getClass() == Account.class);
System.out.println(a instanceof Account);
System.out.println("Navika".getClass().getName());
System.out.println(new int[3].getClass().getSimpleName());
}
}WhatAmI$SavingsAccount
SavingsAccount
Account
true
false
true
java.lang.String
int[]How it works
- The variable is declared as
Account, butgetClass()reports the runtime class,SavingsAccount. getName()gives the full binary name: nested classes show asOuter$Inner.getSimpleName()gives just the class name.SavingsAccount.classis a class literal: theClassobject for a type, written without any object.getClass() == Account.classisfalse: it checks the exact class.instanceof Accountistrue: it accepts subclasses too.- Arrays have classes too:
int[].
getClass() vs instanceof
obj.getClass() == X.class | obj instanceof X | |
|---|---|---|
| Subclass objects | false | true |
null | Throws NullPointerException | false |
| Typical use | Strict equals methods, logging, frameworks | Type checks before casting, pattern matching |
Useful Class Methods
| Method | Returns for SavingsAccount |
|---|---|
getName() | WhatAmI$SavingsAccount (in a package: com.x.WhatAmI$SavingsAccount) |
getSimpleName() | SavingsAccount |
getSuperclass() | The Class for Account |
getInterfaces() | The interfaces it implements |
getPackageName() | The package, or "" for the unnamed package |
isInstance(obj) | Same as obj instanceof SavingsAccount |
These are the entry points to reflection (covered later in the course), which frameworks use to inspect classes at runtime.
Common Mistakes
Calling getClass() on a possibly null reference. It throws; check for null or use instanceof.
Using getClass() == where subclasses should match. That rejects every subclass.
Comparing class names as strings. Compare Class objects with ==; names can clash across packages.
Practice
- Easy: Print
getClass().getSimpleName()for42,42L,4.2,'x'and"x"(each boxed to an object). - Harder: Write
static String typeReport(Object o)that returns the simple name, the superclass's simple name and whether the object is aNumber.
Key Takeaways
Was this tutorial helpful?