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


当前回答

参考代码:

public class sample 
{
  public static void main(String[] args) 
  {
    Object obj=new Object();
    int a=10,b=0;
    obj=a;
    b=(int)obj;

    System.out.println("Object="+obj+"\nB="+b);
  }
}

其他回答

对象变量;hastaId

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

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

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

必须将其强制转换为Integer (int的包装类)。然后,您可以使用Integer的intValue()方法来获取内部整型。

假设对象是一个Integer对象,那么你可以这样做:

int i = ((Integer) obj).intValue();

如果对象不是Integer对象,则必须检测类型并根据其类型进行转换。

首先使用instanceof关键字进行检查。如果为真,则转换它。

参考代码:

public class sample 
{
  public static void main(String[] args) 
  {
    Object obj=new Object();
    int a=10,b=0;
    obj=a;
    b=(int)obj;

    System.out.println("Object="+obj+"\nB="+b);
  }
}