某些特定泛型类型的if-else怎么办? [英] How to do if-else for some specific generic type?
本文介绍了某些特定泛型类型的if-else怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 MyClass
,我想同时调用 mySubMethod(key)
和 mySubMethod2 (key)
表示整数,但仅调用 mySubMethod2(key)
表示非整数。
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尝试以下代码,但不起作用。我还尝试将 K == int
更改为其他内容,例如 K ==整数
, K.equals(int)
和 K.equals(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 */
}
}
推荐答案
使用关键字 instanceof
:
if (key instanceof Integer) {
//...
}
也,您可以删除空的 else
语句,而仅使用if语句:
Also, you can remove the empty else
statement and just use an if statement :
if (key instanceof Integer) {
mySubMethod(key);
}
这篇关于某些特定泛型类型的if-else怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文