How to cast an Object to an int

后端 未结 19 1925
长情又很酷
长情又很酷 2020-11-27 09:58

How can I cast an Object to an int in java?

19条回答
  •  醉梦人生
    2020-11-27 10:32

    @Deprecated
    public static int toInt(Object obj)
    {
        if (obj instanceof String)
        {
             return Integer.parseInt((String) obj);
        } else if (obj instanceof Number)
        {
             return ((Number) obj).intValue();
        } else
        {
             String toString = obj.toString();
             if (toString.matches("-?\d+"))
             {
                  return Integer.parseInt(toString);
             }
             throw new IllegalArgumentException("This Object doesn't represent an int");
        }
    }
    

    As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.

提交回复
热议问题