H42
H42

Reputation: 825

How to do if-else for some specific generic type?

I have MyClass and I want to call both mySubMethod(key) and mySubMethod2(key) for integer, but only call mySubMethod2(key) for non-integer.

I tried below codes but doesn't work. I also tried to change K == int to something else, e.g. K == Integer, K.equals(int) and K.equals(Integer) etc., but all of them don't work. How Can I fix it? Thanks.

public class MyClass<K,V> {

    public boolean myMethod(K key) {
        if (K == int) {
            mySubMethod(key);
        }else {
            // do nothing
        }
        mySubMethod2(key);
        return false;
    }

    public void mySubMethod(K key) {
        /** something */ 
    }

    public void mySubMethod2(K key) {
        /** something */ 
    }

}

Upvotes: 0

Views: 755

Answers (1)

Matteo NNZ
Matteo NNZ

Reputation: 12695

Use the keyword instanceof:

if (key instanceof Integer) {
    //...
}

Also, you can remove the empty else statement and just use an if statement :

if (key instanceof Integer) {
    mySubMethod(key);
}

Upvotes: 5

Related Questions