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

我只是一个虾纸丫 提交于 2020-07-23 06:18:09

问题


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

}

回答1:


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


来源:https://stackoverflow.com/questions/62985630/how-to-do-if-else-for-some-specific-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!