空指針異常(Null Pointer Exception)是我們平時最容易碰到的,也是最令人討厭的異常。本文介紹如何避免出現空指針異常。
首先我們看如下的示例
private Boolean isFinished(String status) {
if (status.equalsIgnoreCase("Finish")) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
private Boolean isFinished(String status) {
if ("Finish".equalsIgnoreCase(status)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
接下來我將接著提供幾種避免空指針的建議。
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
另外一種使用方法
assert expression1:expression2
示例:
public static String getManager(String employeeId) {
assert (employeeId != null) : "employeeId must be not null";
return "qiyadeng";
}
注意記得使用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";
}
5.異常處理
使用try catch處理異常或是檢查變量是否為空。
public static String getManager(String employeeId) {
return null;
}
String managerId = getManager("A015");
System.out.println(managerId.toString());
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包中的類,我們可以使用該類來避免空指針異常。
例如 StringUtils.isEmpty(),StringUtils.isBlank,StringUtils.equals()等等,更多的你可以參考文檔。
為了不出現空指針異常,在寫代碼的過程中需要時刻檢查你的代碼是否會拋出NullPointerException,如果你沒有時間及時調整的話,使用//TODO標記,便于你后面解決問題。
原創文章,轉載請注明: 轉載自http://www.qiyadeng.com/