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


当前回答

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

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

其他回答

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

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

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

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

不可能做到。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;

参考代码:

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