NullPointerException (NPE) 是 Java 開發中最常見、最令人頭疼的異常。本文總結 7 種有效避免 NPE 的編程技巧,幫助你寫出更健壯的代碼。
錯誤: status.equalsIgnoreCase("Finish") —— 若 status 為 null 拋出 NPE。
正確: "Finish".equalsIgnoreCase(status) —— 字面量不為 null,安全調用。
錯誤: 返回 null 導致調用者需判空。
正確: 返回 Collections.EMPTY_LIST、EMPTY_SET、EMPTY_MAP 等不可變空集合。
public static List getEmployees() {
return Collections.EMPTY_LIST; // 而非 null
}
使用 isEmpty()、contains()、containsKey()、hasNext() 等方法先行檢查,避免直接操作可能為 null 的引用。
Java 1.4+ 提供 assert 關鍵字,在開發/測試階段驗證前置條件。
public static String getManager(String employeeId) {
assert (employeeId != null) : "employeeId must be not null";
return "qiyadeng";
}
運行時需加 -enableassertion 參數啟用。
org.springframework.util.Assert 提供豐富的驗證方法,拋出 IllegalArgumentException 信息更清晰。
Assert.notNull(employeeId, "employeeId must be not null");
Assert.hasLength(employeeId, "employeeId must has length greater than 0");
對可能返回 null 的方法調用,使用 try-catch 捕獲 NPE 或調用前 if (obj != null) 判斷。
不推薦: findViewObject("VO").getCurrentRow().getAttribute("Attr") —— 任一環節為 null 都難以定位。
推薦: 分步賦值中間變量,便於調試和加入判空邏輯。
StringUtils.isEmpty()、isBlank()、equals() 等靜態方法內部已處理 null,調用安全。
// TODO 標記便於後續處理。