public class Test<T>{
public boolean isMember(T item) {
if(item instanceof Test)
{
return true;
}
return false;
}
}
Is this the correct way to check if the item is an instance of the class?
I went through some searches and it seems that for a generic class, this will not 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 .
6. instanceof and Generics. Instance tests and casts depend on inspecting the type information at runtime. Therefore, we can't use instanceof along with erased generic types.
Only reference types can be used to declare or instantiate a generic class. int is not a reference type, so it cannot be used to declare or instantiate a generic class. You must use the corresponding wrapper class to instantiate a generic class with a primitive type argument.
To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.
It's unclear what you're trying to test here, but here are a few possibilities:
item
a T
? Yes. Otherwise, it presumably couldn't be passed into the isMember
method. The compiler would disallow it. (See Alex's caveat in the comments below.)Is item
a Test
? Your isMember
method as it is written would test this, but I'm sensing a code smell here. Why would you expect a T
to also be a Test
, 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
a Test<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With