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


当前回答

你不能。int不是Object。

虽然整数是一个对象,但我怀疑这是你的意思。

其他回答

首先使用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);
  }
}

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

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

 int num = i; //Java 1.5 or higher

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

int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
    ArrayList list = null;
    Statement statement = conn.createStatement();
    ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
    while (result.next()) {
        list.add(result.getInt(1));
    }
    statement.close();
    int id[] = new int[list.size()];
    for (int i = 0; i < id.length; i++) {
        try {
            id[i] = ((Integer) list.get(i)).intValue();
        } catch(NullPointerException ne) {
        } catch(ClassCastException ch) {}
    }
    return id;
}
// enter code here

这段代码说明了为什么ArrayList很重要,以及为什么要使用它。简单地从Object转换int。可能会有帮助。