【问题标题】:How to find the type of an Object and then work accordingly?如何找到对象的类型然后相应地工作?
【发布时间】:2013-04-05 06:16:45
【问题描述】:

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

Demo.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
       }
  }

【问题讨论】:

标签: java object


【解决方案1】:

如果您想找到对象的确切类型,可以使用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 的“catch all”方法来避免这个问题;

public Double abs(Double O){
   ...
}
public String abs(String O){
   ...
}
public Long abs(Long O){
   ...
}
public Integer abs(Integer O){
   ...
}

【讨论】:

    【解决方案2】:

    只需进行 insatnceof 测试:

    if(o insatnceof Integer) {
    //abs(int)
    }
    else if(o instanceof Double){
    //abs(double)
    }
    .....
    

    【讨论】:

      【解决方案3】:

      尝试改用instanceof 运算符。

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

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

      更多信息请参见What is the difference between instanceof and Class.isAssignableFrom(...)?

      【讨论】:

        【解决方案4】:

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

        public Object abs(Object O){
           if(Number.class.isAssignableFrom(O.getClass()))
           {
        
               if(O instanceof Integer) {
                    ....
               }
               else if(O instanceof Double) {
                    ....
               }
               .....
        
           }
           else
           {
                 return -1
           }
        

        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-19
          • 1970-01-01
          • 1970-01-01
          • 2021-07-31
          • 2017-01-11
          • 1970-01-01
          • 2022-07-01
          相关资源
          最近更新 更多