HOWTO · Java

如何在 Java 中將 Object 轉換為 int

了解在 Java 中從 Object 取得 int 的四種方法:轉型 Integer、使用 Number.intValue()、呼叫 Integer.intValue(),或剖析整數文字。

本頁內容

要在 Java 中從 Object 取得 int,首先要確定該值的執行階段型別。當它包含 Integer 時,將其轉型並拆箱;對於其他數值包裝類別,使用 Number.intValue();或使用 Integer.parseInt() 剖析其文字。這些方法不可互換:僅憑 Object 參照並不能保證它是數值。
型別轉換是 Java 教學 的主題分組之一,轉換類指南都匯集在一處。

以下範例在所提供的證據中未經執行;其所述值是根據所示的 Java 轉換得出的。

在 Java 中使用 Integer 包裝類別將 Object 轉換為 int

當物件包含 Integer 時,先轉型再指派給 int,既會檢查包裝型別,也會拆箱其值。以下方法會為所提供的物件返回値 123:

public class Main {
  public static int objectToInt(Object obj) {
    return (Integer) obj;
  }

  public static void main(String[] args) {
    Object obj = Integer.valueOf(123);
    int value = objectToInt(obj);
    System.out.println("The converted int is " + value);
  }
}

轉型要求執行階段值必須是 Integer;其他類別會導致 ClassCastException。如果 obj 為 null,轉型會得到 null,將其拆箱為 int 會導致 NullPointerException。如果輸入不確定,請檢查該值或處理這些情況。

在 Java 中使用 Number 和 intValue() 函式將 Object 轉換為 int

當物件可以容納不同的數值包裝型別(例如 Integer、Long 或 Double)時,使用 Number。執行階段值仍必須是 Number。intValue() 返回一個 int;對於超出 int 範圍或帶有小數部分的值,轉換可能會遺失資訊。在此範例中,返回的值為 123:

public class Main {
  public static int objectToInt(Object obj) {
    return ((Number) obj).intValue();
  }

  public static void main(String[] args) {
    Object obj = Double.valueOf(123.9);
    int value = objectToInt(obj);
    System.out.println("The converted int is " + value);
  }
}

這會轉換數值;它不會剖析像 "123" 這樣的字串。非 Number 物件無法轉型為 Number。

在 Java 中使用 Integer 和 intValue() 函式將 Object 轉換為 int

這種形式專門用於執行階段值為 Integer 的物件。它使用 intValue() 明確指出拆箱步驟,儘管將轉型後的 Integer 直接指派給 int 通常會自動完成相同的工作。該方法對此輸入返回 123:

public class Main {
  public static int objectToInt(Object obj) {
    return ((Integer) obj).intValue();
  }

  public static void main(String[] args) {
    Object obj = Integer.valueOf(123);
    int value = objectToInt(obj);
    System.out.println("The converted int is " + value);
  }
}

與直接轉型一樣,不同的執行階段型別會導致 ClassCastException,而 null 的 Integer 在呼叫 intValue() 時會導致 NullPointerException。當其他數值包裝型別也是有效輸入時,請使用更寬泛的 Number 形式。

在 Java 中使用 Integer.parseInt() 函式將 Object 轉換為 int

剖析適用於表示十進位整數的文字。使用 toString() 將物件轉換為文字,然後將該字串傳給 Integer.parseInt()。對於字串 "123",剖析會返回 int 值 123:

public class Main {
  public static int objectToInt(Object obj) {
    return Integer.parseInt(obj.toString());
  }

  public static void main(String[] args) {
    Object obj = "123";
    int value = objectToInt(obj);
    System.out.println("The converted int is " + value);
  }
}

文字必須是 int 範圍內的有效十進位表示;否則 Integer.parseInt() 會擲出 NumberFormatException。這是剖析文字,而不是轉型數值物件。null 物件也無法透過 toString() 提供文字。

結論

根據 Object 實際包含的內容選擇轉換方式:轉型並拆箱 Integer,對其他數值包裝類別使用 Number.intValue(),或當其文字表示整數時使用 Integer.parseInt()。當已知物件包含 Integer 時,直接轉型是最簡單的方法。當執行階段型別和可為 null 性不確定時,請驗證或處理它們。