Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java instanceof implements/extends

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 Listor 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?

like image 660
Jaanus Avatar asked Dec 07 '12 11:12

Jaanus


People also ask

Does Instanceof work with interfaces?

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.

Does Instanceof check superclass?

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.

How does java Instanceof work?

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 .

Does Instanceof work for subclasses?

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.


1 Answers

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
      }
  }
like image 185
Thilo Avatar answered Sep 21 '22 20:09

Thilo