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


当前回答

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

其他回答

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

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

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

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

参考代码:

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

不可能做到。int不是一个对象,它是一个基本类型。你可以将它转换为Integer,然后获取int。

 Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class

 int num = i; //Java 1.5 or higher
so divide1=me.getValue()/2;

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