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
