If class B
and class C
extend class A
, and I have an object that could be an instance of either B
or C
, how can I use check object type Java techniques to determine its exact class?
The simplest and most common way to check an object’s type in Java is using the instanceof operator. It allows you to determine whether an object is an instance of a specific class or its subclass.
Example Usage:
if (obj instanceof B) {
System.out.println("Object is an instance of B");
} else if (obj instanceof C) {
System.out.println("Object is an instance of C");
} else {
System.out.println("Object is not an instance of B or C");
}
Why use instanceof?
- It works at runtime and correctly identifies subclasses.
- It prevents ClassCastException, unlike direct casting.
- It is straightforward and widely used.
The instanceof approach works well, but it returns true for parent classes too, which might not always be desirable.
If you only want to check for the exact class (without considering inheritance), use getClass() instead:
if (obj.getClass() == B.class) {
System.out.println("Exact type is B");
} else if (obj.getClass() == C.class) {
System.out.println("Exact type is C");
}
Differences from instanceof:
-
getClass() only matches the exact class (not subclasses).
-
Safer when you don’t want superclass matches.
-
Doesn’t work well for polymorphic checks.
Sometimes, you might not know all subclasses in advance (e.g., working with dynamic class loading or plugins).
In such cases, reflection can be useful:
System.out.println("Class name: " + obj.getClass().getSimpleName());
System.out.println("Superclass: " + obj.getClass().getSuperclass().getSimpleName());
For a more dynamic approach, use:
Class<?> clazz = obj.getClass();
while (clazz != null) {
System.out.println("Class: " + clazz.getName());
clazz = clazz.getSuperclass();
}
When to use reflection?
- When working with dynamically loaded classes.
- When debugging or logging detailed type hierarchy.
- Slower than instanceof and getClass().