如何優(yōu)雅的判斷對(duì)象的字段屬性值呢?
直接上代碼(工具類,拿去就能用)
...
public static boolean allFieldIsNULL(Object source, List<String> excludeNames){
boolean flag = true;
try {
// 取到obj的class, 并取到所有屬性
Field[] fs = source.getClass().getDeclaredFields();
// 遍歷所有屬性
for (Field f : fs) {
// 設(shè)置私有屬性也是可以訪問的
f.setAccessible(true);
// 1.排除不包括的屬性名, 2.屬性值為空, 3.屬性值轉(zhuǎn)換成String為""
if (null != excludeNames){
if(!excludeNames.contains(f.getName())) {
if ((f.get(source) == null || "".equals(f.get(source).toString()))){
flag = false;
break;
}
}
}else {
if ((f.get(source) == null || "".equals(f.get(source).toString()))){
flag = false;
break;
}
}
}
} catch (Exception e) {
log.error("判斷對(duì)象屬性為空異常", e);
}
return flag;
}
...
參數(shù)
1.source:需要校驗(yàn)的實(shí)體
- excludeNames:不需要校驗(yàn)的屬性集合