liveBook · Manning

getClass

As explained in 100 Java Mistakes and How to Avoid Them

getClass is the Object method that returns the runtime class of the object on which it is invoked.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Distinguishes exact-class checks from instanceof, then examines Calendar, enum, annotation, and Class-object edge cases.
Examples
Demonstrates ArrayList checks, Calendar conversion, customized enum constants, reflective annotations, and a misleading Class-object diagnostic.
What it assumes
Assumes familiarity with Java objects, inheritance, class literals, enums, annotations, and basic reflection.
What you can do after
Diagnose exact-class mistakes, choose instanceof or specialized APIs, and verify questionable static-analysis warnings with tests.
How it connects
Connects getClass() with instanceof, subclasses, reflection, equals(), enums, annotations, proxies, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.