說到在Java中處理「nulls」的最佳實踐(特別是「List」返回),從實體類的getMethod返回「Collections.emptyList()」是一個好習慣?或者我們應該保持實體/數據類/方法整潔乾淨,並且始終返回其值(即使爲空),然後在代碼中的其他位置處理null;使用Collections.emptyList()和null處理
Class Reference{
private Reference reference;
@XmlElement(name = "Reference")
public List<Reference> getReference() {
if(reference==null){
return Collections.emptyList();
}
return reference;
}
public void setReference(List<Reference> reference) {
this.reference = reference;
}
}
或更好地處理空「之後」我使用基本的get方法?
編輯/警告:只爲我的情況我注意到這種方法崩潰我的代碼我不知道爲什麼,當我稍後調用;
References ref= (References) jaxbUnmarshaller.unmarshal(xmlReader)
我得到一個不支持的操作異常,但是當我從清理我collections.emtpyList工作getMethod確定。所以用@XmlElement標籤
謝謝所有偉大的建議,我們可以說,在實體類的方法,這空處理,也適用於非列表類型,如字符串或整數? – Spring
只有當您明確希望變量爲空時,纔會使用Integer而不是int。否則,使用int是一個更好的選擇。關於字符串,null通常用於表示該屬性未設置,而不是空字符串。但是調用者通常不會迭代String字符。 –
只爲我的情況這種方法崩潰我的代碼我不爲什麼,當我以後調用(引用)jaxbUnmarshaller.unmarshal(xmlReader)。我得到一個不受支持的操作異常,並工作時,我從collections.emtpyList清理我的getMethod .. – Spring