Search code examples
javagenericscastingpolymorphismgeneric-programming

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 */ 
    }

}

Solution

  • 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);
    }