liveBook · Manning

Class.isInstance

As explained in 100 Java Mistakes and How to Avoid Them

Class.isInstance is a reflection API method that tests whether an object is an instance of the represented runtime class or one of its subclasses.

Class.isInstance tests whether an object belongs to the represented runtime class or one of its subclasses. It is useful when the class is known only at runtime, and it returns false for a null argument. section 5.1.3 section 9.6

Guarding a nullable object

default void processObject(@Nullable Object obj, @NotNull Class<?> cls) { if (!cls.isInstance(obj)) return; int hash = obj.hashCode(); // Process hash } section 5.1.3

The null result is significant for both control flow and static analysis: after a failed isInstance check, execution cannot reach the dereference when the object is null. IntelliJ IDEA can model this with the contract @Contract("null -> false"). section 5.1.3

Avoid confusing runtime-class equality with an instance test:

  • Use cls.isInstance(object) when cls is unavailable at compile time. section 9.6
  • Choose between exact-class behavior and subclass-inclusive behavior deliberately; getClass() equality excludes subclasses, whereas instanceof and isInstance support subclass checks. section 9.6
  • Comment intentional getClass() usage, and declare classes final by default when inheritance is not intended. section 9.6
default void processObject(@Nullable Object obj, 
                           @NotNull Class<?> cls) {
  if (!cls.isInstance(obj)) return;
  int hash = obj.hashCode();
  … // Process hash
}

Inspect the nullable-object guard and its safe dereference after Class.isInstance returns true. section 5.1.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains subclass behavior, null control flow, and static-analysis contracts without descending into reflection internals.
Examples
Uses a nullable Object guard and contrasts getClass() equality with instanceof for ArrayList checks.
What you can do after
Apply it to guard nullable objects and perform runtime type checks without accidentally excluding subclasses.
How it connects
Connects runtime type testing with instanceof, getClass(), nullability annotations, 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.