How does instanceof work exactly? When I have a hierarchy of objects that extend and implement eachother, does being instance of something work through these both lines?
For example I want to know if my object is instance of List
or ArrayList
or Collection
?
I examined this tree, http://docs.oracle.com/javase/6/docs/api/java/util/package-tree.html
And they seem to fall all under Object
ofcourse, but what I need, I think is AbstractCollection
or even normal Collection
, because that seems to be the highest in hierarchy.
Will I be fine, when I check an object against only Collection
to cover all those 3 classes?
instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.
Using instanceof operator, when a class extends a concrete class. When a class extends a concrete class, the instanceof operator returns true when a subclass object is checked against its concrete superclass-type.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Will I be fine, when I check an object against only Collection to cover all those 3 classes?
Yes, instanceof Collection
will return true for all implementation (direct or indirect) of the Collection interface.
In the rare case that you do not want this, you'd have to use reflection. For example, Class#getDeclaredClasses will give you a list of all classes and interfaces that are directly extended/implemented by the class.
Once you know that something is a Collection, you can cast it to get access to its methods (like iterator
):
if (myObject instanceof Collection){
Collection<?> c = (Collection<?>) myObject;
for (Object o: c){
// do something with every element in the collection
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With