How to Determine an Object's Class?
If Class B and Class C Extend Class a and I Have an Object of Type B or C, How Can I Determine of Which Type It Is an Instance? 2 12 Answers If (Obj Instanceof...
If class B and class C extend class A and I have an object of type B or C, how can I determine of which type it is an instance?
12 Answers
if (obj instanceof C) {
//your code
}
Use Object.getClass. It returns the runtime type of the object.
Multiple right answers were presented, but there are still more methods: Class.isAssignableFrom() and simply attempting to cast the object (which might throw a ClassCastException).
Possible ways summarized
Let's summarize the possible ways to test if an object obj is an instance of type C:
// Method #1
if (obj instanceof C)
;
// Method #2
if (C.class.isInstance(obj))
;
// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
;
// Method #4
try {
C c = (C) obj;
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
// Method #5
try {
C c = C.class.cast(obj);
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}