自動拆箱空物件到基元的陷阱
public class Foobar {
public static void main(String[] args) {
// example:
Boolean ignore = null;
if (ignore == false) {
System.out.println("Do not ignore!");
}
}
}
這裡的缺陷是將 null 與 false 進行比較。由於我們將原始 boolean 與 Boolean 進行比較,因此 Java 試圖將 Boolean Object 拆分為原始等價物,準備進行比較。但是,由於該值為 null,因此會丟擲 NullPointerException。
Java 無法將原始型別與 null 值進行比較,這會在執行時產生 NullPointerException。考慮條件 false == null 的原始情況; 這會產生編譯時錯誤 incomparable types: int and <null>。