문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top