0到1快速掌握Java全栈开发,玩转微信生态
download:
链接:pan.baidu.com/s/1bofTWdbJ… 提取码:na7o --来自百度网盘超级会员V4的分享
一、前言
今天和小同伴们分享一个常用的工具类,共计四个办法,运用场景比拟普遍,有用于校验某个对象或对象中指定属性为空值时,直接返回异常,常用语校验前端恳求参数;也有当值不为空时,执行指定动作,可减少大量的if条件,如:mybatis恳求参数设置;还有用于判别当值不为空时,替代为新值,完成后续动作。
这样描绘可能不够明晰,这里花哥罗列了几个运用场景,更多的场景需求小同伴们依据本人业务需求合理运用。
//场景一,点击登录时,后端校验用户名
if(StringUtils.isEmpty(name)){
throw new Exception("登录用户名不能为空");
}
//场景二:属性内容转换为新值
String address = "浙江省杭州市";
if(StringUtils.isNotEmpty(address)){
address ="地址:"+address;
}
//场景三:替代过多的if条件
SysUserDto userDto = new SysUserDto();//前端参数
SysUser user = new SysUser();//mybatis参数
if(StringUtils.isEmpty(userDto.getName())){
user.setUserName(userDto.getName())
}
if(StringUtils.isEmpty(userDto.getPwd())){
user.setPassword(userDto.getPwd())
}
复制代码
\
二、正文
首先创立一个测试实体类:
import lombok.Data;
@Data
public class SysUser{
private String name;
private String password;
}
复制代码
2.1 检查多个对象不能为空
-
测试范例
SysUser user = new SysUser(); SysUser user2 = null; Args.notEmptys(user,user2); 复制代码
-
办法内容
public static void notEmptys(Object... objects) { for (Object obj : objects) { if (obj == null) { throw new BusinessException("属性不能为空"); } if (obj.toString().trim().isEmpty()) { throw new BusinessException("属性不能为空"); } } } 复制代码
-
测试结果
Exception in thread "main" 属性不能为空 at com.basic.business.utils.Args.notEmptys(Args.java:27) at com.basic.business.demo.DemoController.main(DemoController.java:43) 复制代码
2.2 校验对象属性不能为空
若将参数【Boolean isAll】设置为true,则会校验全部属性;若设置为false,就需求将检测字段放入【propertys】中。
-
测试范例
SysUser user = new SysUser(); //用法一:校验全部参数 Args.checkField(user,true,""); //用法二:只校验password参数 Args.checkField(user,false,"password"); 复制代码
-
办法内容
/**
-
对象多字段判空检查
-
@param obj 被检查的对象
-
@param isAll 能否检查全部参数
-
@param propertys 被检查对象中的字段 可多个 */ public static void checkField(Object obj, Boolean isAll, String... propertys) { if (obj != null) { Class<? extends Object> clazz = obj.getClass();
if (isAll) { PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz); for (int p = 0; p < propertyDescriptors.length; p++) { checkEachField(obj, propertyDescriptors[p]); } } else { if (propertys != null && propertys.length > 0) { //遍历一切属性 for (int i = 0; i < propertys.length; i++) { String property = propertys[i]; //获取属性信息 BeanUtils.getPropertyDescriptors(clazz); PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, property); checkEachField(obj, pd); } } }} } private static void checkEachField(Object obj, PropertyDescriptor pd) { Class clazz = obj.getClass(); String property = pd.getName(); if (pd != null) { //获取当前字段的javabean读办法 Method readMethod = pd.getReadMethod(); if (readMethod != null) { Object invoke = null; try { invoke = readMethod.invoke(obj); } catch (Exception e) { throw new BusinessException("办法 " + readMethod.getName() + "无法执行"); } if (invoke != null) { //String类型单独处置 Class propertyType = pd.getPropertyType(); if ("java.lang.String".equals(propertyType.getName())) { if (StringUtils.isBlank((String) invoke)) { throw new BusinessException("错误 : [ " + property + " ] 不能为空!"); } } else if ("java.util.List".equals(propertyType.getName())) { List list = (List) invoke; if (list.size() == 0) { throw new BusinessException("错误 : [ " + property + " ] 不能为空!"); } } } else { throw new BusinessException("错误 : [ " + property + " ] 不能为空!"); } } else { throw new BusinessException("在 " + clazz + "中 找不到" + "[ " + property + " ] 的 读办法"); } } else { throw new BusinessException("在 " + clazz + "中 找不到" + "[ " + property + " ] 属性"); } } 复制代码
-
-
测试结果
用法一结果: Exception in thread "main" 错误 : [ name ] 不能为空! at com.basic.business.utils.Args.checkEachField(Args.java:116) at com.basic.business.utils.Args.checkField(Args.java:77)
用法二结果: Exception in thread "main" 错误 : [ password ] 不能为空! at com.basic.business.utils.Args.checkEachField(Args.java:116) at com.basic.business.utils.Args.checkField(Args.java:77) 复制代码
2.3 参数不为空时执行指定动作
我们经常会遇到这种场景,依据前端参数来组装数据库查询条件,假如不为空我们就将前端值设置到是实体类中,或者如下面这个例子中,当name不为空时,参加到list当中。
-
测试范例
List list = Lists.newArrayList(); SysUser user = new SysUser(); user.setName("huage"); Args.doIfNotEmpty(user.getName(),list::add); System.out.println(list); 复制代码
-
办法内容
public static <R, T> R doIfNotNull(T t, Callback<T, R> callback) { try { return t == null ? null : callback.call(t); } catch (Exception e) { throw new BusinessException("[doIfNotNull error]", e); } } 复制代码
-
测试结果
[huage] 复制代码
2.4 参数为空时运用新值,并完成指定动作
本办法和2.较为相似,只是当目的值不为空时,运用新值停止后续的操作,如下面这个例子中,name初始值为【test】,执行完doIfNotNullNewValue后会将新值【huage】添加到list中,。
-
测试范例
List list = Lists.newArrayList(); SysUser user = new SysUser(); user.setName("test"); Args.doIfNotNullNewValue(user.getName(),"huage",list::add); System.out.println(list); 复制代码
-
办法内容
public static <R, T> R doIfNotNullNewValue(T t,T newt, Callback<T, R> callback) { try { return t == null ? null : callback.call(newt); } catch (Exception e) { throw new BusinessException("[doIfNotNull error]", e); } } 复制代码
-
测试结果
[huage]