Ninjoe Quah
Ninjoe Quah

Reputation: 399

check if item is instance of a generic class

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.

Upvotes: 9

Views: 9073

Answers (3)

Ninjoe Quah
Ninjoe Quah

Reputation: 399

public class LinkList<T>{

    public boolean isMemberOfClass(T item) {

        if(item instanceof LinkList)
        {
            return true;
        }
        return false;
    }
}

I'm sorry, I'm not suppost to post question as answer.

the class LinkList is a generic class. the function is to check if the item belongs to the class. check if the have the same T.

Upvotes: -1

StriplingWarrior
StriplingWarrior

Reputation: 156748

It's unclear what you're trying to test here, but here are a few possibilities:

  1. Is 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.)
  2. 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.

  3. 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.

Upvotes: 5

GingerHead
GingerHead

Reputation: 8240

T is not a variable, but a place holder for a class that is defined at runtime. Generics are a compile time feature, for that reason they add checks at compile time which may not have any meaning at runtime. We can only check the type of the object referenced at runtime which could be a super class type in the code. If we want to pass the type T as parameter to the method, all we have to do is to approach explicitly like the following:

void genericMethod(Class<T> tClass) {
    if(String.class.isAssignableFrom(tClass)) 

or

void genericMethod(Class<T> tClass, T tArg) {

Note that the type might not be the same as here we can see how to manipulate:

genericMethod(Number.class, 1);

Upvotes: 0

Related Questions