getClass() is an Object method that returns a java.lang.Class mirror for the object's exact runtime class. It is useful for diagnostics, reflection, and some equals() implementations, but it is not interchangeable with instanceof. section 9.6
if (object.getClass() == ArrayList.class) { #1
…
}
if (object instanceof ArrayList) { #2
…
}
Compare exact-class testing with subtype-aware testing: getClass() matches only ArrayList itself, while instanceof also matches subclasses. section 9.6
The practical mistake is choosing an exact-class check when subclasses should be accepted. A Calendar value normally has a concrete subclass such as GregorianCalendar, so comparing its getClass() result with the abstract Calendar.class is never true. The intended conversion is therefore skipped. section 9.6
Exact class versus subtype
Use getClass() when the distinction between a class and every subclass is deliberate, such as preserving an existing java.sql.Date while converting another date type. Use instanceof when any compatible subtype should match. Ask whether subclasses are possible and which behavior is intended. section 9.6
Treat these cases as additional getClass() hazards:
- An enum constant with a class body has an implicit anonymous subclass, so use getDeclaringClass() when the declaring enum type is required. section 9.7
- An annotation object may be represented by a proxy class, so use annotationType() instead of relying on getClass(). section 9.7
- Calling getClass() on a Class object reports java.lang.Class, not the represented data type; inspect the actual data object instead. section 9.7
- Static analysis can identify simple always-false conditions, but confirm a disputed warning with a unit test. section 9.6
