1

我有一个方法可以传递任何类型的参数。我的目标是找到传递的参数是否是数字,然后找到数字的绝对值。传递的对象可以是double、Integer、string、long等。

演示.java

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
       }
  }
4

4 回答 4

2

只需做一个insatnceof测试:

if(o insatnceof Integer) {
//abs(int)
}
else if(o instanceof Double){
//abs(double)
}
.....
于 2013-04-12T16:13:40.743 回答
2

如果您想找到对象的确切类型,可以使用if-then-elses 链,如下所示:

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然而,这听起来像是一个糟糕的设计选择:考虑使用重载方法来代替首先避免这个问题的“包罗万象”方法;

public Double abs(Double O){
   ...
}
public String abs(String O){
   ...
}
public Long abs(Long O){
   ...
}
public Integer abs(Integer O){
   ...
}
于 2013-04-12T16:14:56.937 回答
0

尝试改用instanceof运算符。

if ( O instanceof Number ) {
  return Math.abs(((Number)O).doubleValue());
}

您的要求越来越高 - 可以转换为double吗?

请参阅instanceof 和 Class.isAssignableFrom(...) 有什么区别?了解更多信息。

于 2013-04-12T16:13:02.347 回答
0

您在这里寻找的关键字可能是instanceof

public Object abs(Object O){
   if(Number.class.isAssignableFrom(O.getClass()))
   {

       if(O instanceof Integer) {
            ....
       }
       else if(O instanceof Double) {
            ....
       }
       .....

   }
   else
   {
         return -1
   }

}

于 2013-04-12T16:14:19.717 回答