check if item is instance of a generic class
It's unclear what you're trying to test here, but here are a few possibilities:
- Is
item
aT
? Yes. Otherwise, it presumably couldn't be passed into theisMember
method. The compiler would disallow it. (See Alex's caveat in the comments below.) Is
item
aTest
? YourisMember
method as it is written would test this, but I'm sensing a code smell here. Why would you expect aT
to also be aTest
, but only some of the time? You may want to reconsider how you're organizing your classes. Also, if this is really what you want, then your method could be written as:public boolean isMember(T item) { return (item instanceof Test); }
Which begs the question: why have a method like this in the first place? Which is easier to write?
if(obj instanceof Test) {...}
or
if(Test<Something>.isMember(obj)) {...}
I would argue that the first one is simpler, and most Java developers will understand what it means more readily than a custom method.
Is
item
aTest<T>
? There is no way to know this at run time because Java implements generics using erasure. If this is what you want, you'll have to modify the method signature to be like Mike Myers's example.