null 指標異常(Null Pointer Exception)是我們平時最容易碰到的,也是最令人討厭的異常。本文介紹如何避免出現null 指標異常。
首先我們看如下的樣本
private Boolean isFinished(String status) { if (status.equalsIgnoreCase("Finish")) { return Boolean.TRUE; } else { return Boolean.FALSE; } }
如果status的值為空白的話,那麼將會出現null 指標異常(本例第2行)。所以我們應該使用如下的方法
private Boolean isFinished(String status) { if ("Finish".equalsIgnoreCase(status)) { return Boolean.TRUE; } else { return Boolean.FALSE; } }
這樣的話,如果status為空白,也不會出現null 指標異常。相信我們大多數朋友已經知道這樣的方法了,如果一個對象可能為null,那麼不需要直接調用它的方法。
接下來我將接著提供幾種避免null 指標的建議。
1.判斷Collection是否為空白。
2.使用一些判斷方法。
3.assert關鍵字。
4.Assert類。
5.異常處理。
6.太多的點.操作文法。
7.使用StringUtils類
1.判斷Collection是否為空白
Collection 為空白是指Collection中沒有元素。一些開發人員如果碰到Collection中沒有元素的時候,經常return null,更好的做法是,你應該return Collections.EMPTY_LIST,Collections.EMPTY_SET或者是Collections.EMPTY_MAP.
錯誤的代碼
public static List getEmployees() { List list = null; return list; }
正確的代碼
public static List getEmployees() { List list = Collections.EMPTY_LIST; return list; }