CKTIS / Java
Class.isInstance — check an object's type at runtime
Use `Class.isInstance` when the target type is held in a `Class<?>` variable and you want to check an object before casting it.
Version: Java SE 21
Syntax
public boolean isInstance(Object obj)Class.isInstance is an instance method of java.lang.Class. type.isInstance(value) returns true when value is non-null and can be cast to the reference type represented by type. It does not require an exact class match: subclasses, interface implementations, and compatible array types can match. For example, Object[].class.isInstance(new String[0]) returns true.
A null argument or an incompatible object gives false. So does int.class.isInstance(42): 42 is boxed as an Integer, and a primitive type has no object instances. A null argument is different from type itself being null, which makes the call throw NullPointerException.
When the target type is known as you write the code, value instanceof String s gives you a variable s on a match. When the type is passed in as a Class<T>, use type.isInstance(value) and call type.cast(value) on the same object after a true result to obtain a value of type T. The test alone does not narrow the declared type of value. Without the guard, cast throws ClassCastException for an incompatible object, but returns null for null.
target.isAssignableFrom(source) compares two Class objects: it asks whether the source type can be assigned to the target type. target.isInstance(value) checks an actual object instead. Because of type erasure, List.class.isInstance(value) can identify a list, but it cannot establish that it is a List<String> or check its elements.
Examples
public class Main {
static void printLength(Class<CharSequence> type, Object value) {
if (!type.isInstance(value)) {
System.out.println("rejected");
return;
}
CharSequence text = type.cast(value);
System.out.println("length=" + text.length());
}
public static void main(String[] args) {
Class<CharSequence> type = CharSequence.class;
printLength(type, "Java");
printLength(type, new StringBuilder("API"));
printLength(type, 21);
printLength(type, null);
}
}Result
length=4 length=3 rejected rejected
`String` and `StringBuilder` implement `CharSequence`, so the program prints the length of each. The `Integer` and `null` fail the guard, so the program never calls `cast` for them.
Related lessons
- Java · Lesson 36 · Intermediate · Version: 2
- Java · Lesson 37 · Intermediate · Version: 2