【java工具類】引數校驗工具類java判斷是否為空
技術標籤:java工具類解決各種場景的實際需要
目錄
前言:
經常要遇到判斷各種是否為空的情況,String有lang3的StringUtils,CollectionUtils。為啥子不能直接的放進一個工具類處理呢?這樣業務的呼叫不是更為的簡潔方便呢?對於JVM的優化也是好事情的呀!沒有必要不斷的編譯第三方的jar和class檔案呀
引數校驗工具類:封裝在一個公有方法裡面
/**
* 物件是否不為空(新增)
* @Date 2018/3/18 21:57
*/
public static boolean isNotEmpty(Object o) {
}
/**
* 物件是否為空
*
* @Date 2018/3/18 21:57
*/
public static boolean isEmpty(Object o) {
if (o == null) {
return true;
}
if (o instanceof String) {
if ("".equals(o.toString().trim())) {
return true;
}
} else if (o instanceof List) {
return true;
}
} else if (o instanceof Map) {
if (((Map) o).size() == 0) {
return true;
}
} else if (o instanceof Set) {
if (((Set) o).size() == 0) {
return true;
}
} else if (o instanceof Object[]) {
return true;
}
} else if (o instanceof int[]) {
if (((int[]) o).length == 0) {
return true;
}
} else if (o instanceof long[]) {
if (((long[]) o).length == 0) {
return true;
}
}
return false;
}
/**
* 物件組中是否存在空物件
* @Date 2018/3/18 21:59
*/
public static boolean isOneEmpty(Object... os) {
for (Object o : os) {
if (isEmpty(o)) {
return true;
}
}
return false;
}
/**
* 物件組中是否全是空物件
* @Date 2018/3/18 21:59
*/
public static boolean isAllEmpty(Object... os) {
for (Object o : os) {
if (!isEmpty(o)) {
return false;
}
}
return true;
}
應用案例:
private void saveDept(Dept dept) {
if(ValidateUtil.isEmpty(dept.getPid())){
log.error("此時部門老大不同意,不許新增部門操作:{}",dept.getDescription());
}
}
完整的java類資訊:
public class ValidateUtil {
/**
* 物件是否不為空(新增)
*
*
* @Date 2018/3/18 21:57
*/
public static boolean isNotEmpty(Object o) {
return !isEmpty(o);
}
/**
* 物件是否為空
*
*
* @Date 2018/3/18 21:57
*/
public static boolean isEmpty(Object o) {
if (o == null) {
return true;
}
if (o instanceof String) {
if ("".equals(o.toString().trim())) {
return true;
}
} else if (o instanceof List) {
if (((List) o).size() == 0) {
return true;
}
} else if (o instanceof Map) {
if (((Map) o).size() == 0) {
return true;
}
} else if (o instanceof Set) {
if (((Set) o).size() == 0) {
return true;
}
} else if (o instanceof Object[]) {
if (((Object[]) o).length == 0) {
return true;
}
} else if (o instanceof int[]) {
if (((int[]) o).length == 0) {
return true;
}
} else if (o instanceof long[]) {
if (((long[]) o).length == 0) {
return true;
}
}
return false;
}
/**
* 物件組中是否存在空物件
*
*
* @Date 2018/3/18 21:59
*/
public static boolean isOneEmpty(Object... os) {
for (Object o : os) {
if (isEmpty(o)) {
return true;
}
}
return false;
}
/**
* 物件組中是否全是空物件
*
*
* @Date 2018/3/18 21:59
*/
public static boolean isAllEmpty(Object... os) {
for (Object o : os) {
if (!isEmpty(o)) {
return false;
}
}
return true;
}
}