How to find the type of an Object and then work accordingly?
我有一个可以传递任何类型参数的方法。我的目标是发现传递的参数是否为数字,然后找到数字的绝对值。传递的对象可以是double,Integer,string,long等。
演示程序
1 2 3 4 5 6 7 8 9 10 11 12
| public class Demo {
public Object abs (Object O ){
if(Number. class. isAssignableFrom(O. getClass())){
// Check the type of the number and return the absolute value of the number
}
else
{
return -1
}
} |
- stackoverflow.com/questions/106336/…应该回答这个问题。
如果要查找对象的确切类型,可以使用if-then-else链,如下所示:
1 2 3 4 5 6
| Class <? extends Object > cls = O. getClass();
if (cls == Integer. class) {
} else if (cls == String. class) {
} else if (cls == Long. class) {
} else if (cls == Double. class) {
} ... |
但是,这听起来似乎是一个糟糕的设计选择:首先考虑使用重载方法代替采用Object的"全部捕获"方法来避免此问题;
只需执行insatnceof测试:
1 2 3 4 5 6 7
| if(o insatnceof Integer) {
//abs(int)
}
else if(o instanceof Double){
//abs(double)
}
..... |
您在此处寻找的关键字可能是instanceof
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public Object abs (Object O ){
if(Number. class. isAssignableFrom(O. getClass()))
{
if(O instanceof Integer) {
....
}
else if(O instanceof Double) {
....
}
.....
}
else
{
return -1
} |
} ??
尝试使用instanceof运算符。
您的要求越来越紧迫-是否可以强制转换为double?
请参阅instanceof和Class.isAssignableFrom(...)之间有什么区别?有关更多信息。