There are many functions defined in Java Standard Library Packages through which you can determine the Instance type of an Object. Below mentioned is a summarized list of such functions:
// 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) {
}
Differences in null handling
There is a difference in null handling though:
- In the first 2 methods expressions evaluate to false if obj is null (null is not instance of anything).
- The 3rd method would throw a NullPointerException obviously.
- The 4th and 5th methods on the contrary accept null because null can be cast to any type!
To remember: null is not an instance of any type but it can be cast to any type.
Notes
- Class.getName() should not be used to perform an "is-instance-of" test becase if the object is not of type C but a subclass of it, it may have a completely different name and package (therefore class names will obviously not match) but it is still of type C.
- For the same inheritance reason Class.isAssignableFrom() is not symmetric:
obj.getClass().isAssignableFrom(C.class) would return false if the type of obj is a subclass of C.