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; } 2.使用一些判斷方法
使用一些方法如contains(),indexOf(),isEmpty(),containsKey(),ContainsValue和hasNext()等來判斷,確保不存在空值。
樣本:
String myName = "qiyadeng"; List list = Collections.EMPTY_LIST; boolean exist = list.contains(myName); int index = list.indexOf(myName); boolean isEmpty =list.isEmpty(); Map map =Collections.EMPTY_MAP; exist=map.containsKey(myName); exist=map.containsValue(myName); isEmpty=map.isEmpty(); Set set=Collections.EMPTY_SET; exist=set.contains(myName); isEmpty=set.isEmpty(); Iterator iterator; exist = iterator.hasNext();
3.assert關鍵字
在Java1.4版本之後,提供了斷言assert來確定你的代碼中的假設。使用的文法如下:
assert expression1
expression1是一個boolean運算式,如果expression1返回的false,系統將會拋出AssertError(沒有詳細資料)。
另外一種使用方法
assert expression1:expression2
如果expression1返回false,那麼系統將會拋出AssertError,並且詳細資料為expression2。
樣本:
public static String getManager(String employeeId) { assert (employeeId != null) : "employeeId must be not null"; return "qiyadeng"; }
我使用getManager(null)來調用getManger方法,最後啟動並執行結果是"java.lang.AssertionError:employeedId must be not null"
注意記得使用java選項中加入-enableassertion開啟assertion功能。
4.Assert類
Assert類在com.bea.core.repackaged.springframework.util包中,有許多方法可以用於斷言。
public static String getManager(String employeeId) { Assert.notNull(employeeId, "employeeId must be not null"); Assert.hasLength(employeeId, "employeeId must has length greater than 0"); return "qiyadeng"; }
當我同樣使用getManager(null)來調用getManager方法,將獲得資訊"java.lang.IllegalArgumentException: employeeId must be not null"。
5.異常處理
使用try catch處理異常或是檢查變數是否為空白。
public static String getManager(String employeeId) { return null; }
如上代碼,我使用下面方法調用
String managerId = getManager("A015"); System.out.println(managerId.toString());
將會發生"java.lang.NullPointerException",為了處理這個異常,我們應該使用try catch來處理異常或者是檢查變數是否為null。
try-catch方法
String managerId = getManager("A015"); try { System.out.println(managerId.toString()); } catch (NullPointerException npe) { //write your code here }
或者是對變數進行檢查
String managerId = getManager("A015"); if (managerId != null) { System.out.println(managerId.toString()); } else { //write your code here } 6.不要太多的點.操作文法
一些開發人員使用太多的這樣的方法來減少代碼,但是這個對後面的維護和異常處理都是不太好的。
錯誤的寫法
String attrValue = (String)findViewObject("VO_NAME").getCurrentRow().getAttribute("Attribute_NAME");
正確的寫法
ViewObject vo = findViewObject("VO_NAME"); Row row = vo.getCurrentRow(); String attrValue = (String)row.getAttribute("Attribute_NAME");7.使用StringUtils類
StringUtil是org.apache.commns.lang包中的類,我們可以使用該類來避免null 指標異常。
例如 StringUtils.isEmpty(),StringUtils.isBlank,StringUtils.equals()等等,更多的你可以參考文檔。
為了不出現null 指標異常,在寫代碼的過程中需要時刻檢查你的代碼是否會拋出NullPointerException,如果你沒有時間及時調整的話,使用//TODO標記,便於你後面解決問題。
原創文章,轉載請註明: 轉載自http://www.qiyadeng.com/
本文連結地址: 在Java中避免null 指標異常(Null Pointer Exception)