常見的未封裝的api接口我們會這么寫,來判斷這個傳入參數是否為空,來輸出什么什么參數為空
if(Stringutils.isEmpty(vo.getName())) {
return "name參數為空";
}
if(Stringutils.isEmpty(vo.getAge())) {
return "age參數為空";
}
下面使用工具類封裝的方式校驗傳入對象的指定參數是否為空,較為簡便。
缺點:
并沒有對list或者map中的某字段是否為空做判斷,只做了大小和非空的判斷
public class ArrayIsNotNull { public static boolean isNull(Object o) { boolean result = false; if (null == o) { result = true; } else if (o instanceof List) { result = ((List) o).size() == 0; } else if (o instanceof Map) { result = ((Map) o).isEmpty(); } else if (o.getClass() == String.class) { result = isEmpty(o.toString()); } return result; } public static boolean isEmpty(String s) { boolean result=false; if("".equals(s)) { result=true; } return result; } public static void isNullAndThrowExp(String[] msg, Object... o) throws Exception { if (null != o && msg.length>0) { for (int i = 0; i < o.length; i++) { if (isNull(o[i])) { String name=i < msg.length ? msg[i] : ""; System.out.PRintln("第"+i+"個參數"+name+"為空!"); throw new Exception(); } } }else{ System.out.println("傳入對象為null"); throw new Exception(); } } public static void main(String[] args) throws Exception { Student student=new Student(); student.setAge(11); student.setNameString("name"); student.setPeople(true); ArrayList<Object> list=new ArrayList<Object>(); //list.add(""); student.setList(list); Map<Object, Object> map=new HashMap<Object, Object>(); map.put("", ""); student.setMap(map); isNullAndThrowExp(new String[]{"age","nameString","isPeople","list","map"},student,student.getAge(),student.getNameString(),student.isPeople(),student.getList(),student.getMap()); }student對象,get set略public class Student { private String nameString; private int age; private boolean isPeople; private ArrayList<Object> list; private Map<Object, Object> map;
新聞熱點
疑難解答