Steven De Groote
Steven De Groote

Reputation: 2233

Test if Object is a generic list of specific type

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

Answers (1)

Marko Topolnik
Marko Topolnik

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

Related Questions