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


当前回答

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

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

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

其他回答

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

参考代码:

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

我们可以使用下面的代码在Java中转换一个对象为Integer。

int value = Integer.parseInt(object.toString());

答:

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
so divide1=me.getValue()/2;

int divide1 = (Integer) me.getValue()/2;