Alex Rivera | Logout

How to cast an Object to an int

Asked 2010-09-07T18:15:37.363
275

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

Edit
Report

2 Answers

13
@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.

answered 2010-09-07T18:51:02.050
2

You can't. An int is not an Object.

Integer is an Object though, but I doubt that's what you mean.

answered 2010-09-07T18:17:37.590

Your Answer