我如何在java中将对象转换为int型?


当前回答

答:

int i = ( Integer ) yourObject;

如果你的对象已经是一个整数,它将顺利运行。即:

Object yourObject = 1;
//  cast here

or

Object yourObject = new Integer(1);
//  cast here

etc.

如果你的对象是其他类型的对象,你需要先将它(如果可能的话)转换为int类型:

String s = "1";
Object yourObject = Integer.parseInt(s);
//  cast here

Or

String s = "1";
Object yourObject = Integer.valueOf( s );
//  cast here

其他回答

@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");
    }
}

正如你所看到的,这不是一个非常有效的方法。你只需要确定你所拥有的对象类型。然后以正确的方式将其转换为int型。

对象变量;hastaId

Object hastaId = session.getAttribute("hastaID");

例如,将一个对象转换为int类型,即hasaid

int hastaID=Integer.parseInt(String.valueOf(hastaId));

如果你的意思是将String转换为int,请使用Integer.valueOf("123")。

你不能将大多数其他对象强制转换为int型,因为它们没有int值。例如,XmlDocument没有int值。

int i = (Integer) object; //Type is Integer.

int i = Integer.parseInt((String)object); //Type is String.

我在处理来自GSON的数据时使用一行程序:

int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;