常见的未封装的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;
新闻热点
疑难解答