Reputation: 2233
For various reasons, a method of mine accepts a generic Object
argument. What the method does depends on the actual type, so I do some instanceof
Now, in one specific case, I need to check if the type is Iterable.
I have found that instanceof with generics does not work.
x instanceof Iterable<Integer>
So what are the alternatives, apart from looping through each element and testing their type?
Upvotes: 0
Views: 489
Reputation: 200306
If you can't influence the signature of your method or the Iterable instances you get, then there is no way to distinguish an instance of e.g. Iterable<Object>
containing only integers from an instance of Iterable<Integer>
. They are identical in every respect; in fact, the very concept "instance of Iterable<Integer>
" is nebulous for this reason. Instances are runtime artifacts and constructor type parameters are a compile-time artifact.
Upvotes: 5