stringutils 判断对象以及对象内的map list是否为空

stringutils 判断对象以及对象内的map list是否为空

public class ArrayIsNotNull {

	public static void notEmpty(String message,Object obj) {
		if (obj == null){
			throw new IllegalArgumentException(message + " must be specified,obj is null");
		}
		if (obj instanceof String && obj.toString().trim().length()==0){
			throw new IllegalArgumentException(message + " must be specified,String is empty");
		}
		if (obj.getClass().isArray() && Array.getLength(obj)==0){
			throw new IllegalArgumentException(message + " must be specified,Array is empty");
		}
		if (obj instanceof Collection && ((Collection)obj).isEmpty()){
			throw new IllegalArgumentException(message + " must be specified, Collection is empty");
		}
		if (obj instanceof Map && ((Map)obj).isEmpty()){
			throw new IllegalArgumentException(message + " must be specified,Map is empty");
		}
	}
	
	public static boolean isNull(Object obj) {
		boolean result=false;
		if (obj == null){
			result=true;
			return result;
		}
		if (obj instanceof String && obj.toString().trim().length()==0){
			result=true;
			return result;
		}
		if (obj.getClass().isArray() && Array.getLength(obj)==0){
			result=true;
			return result;
		}
		if (obj instanceof Collection && ((Collection)obj).isEmpty()){
			result=true;
			return result;
		}
		if (obj instanceof Map && ((Map)obj).isEmpty()){
			result=true;
			return result;
		}
		return result;
    }
	
	public static void isNullAndThrowExp(String[] msg, Object... o) {
		StringBuffer buffer = new StringBuffer();
		if(msg.length+1 != o.length)
			throw new IllegalArgumentException(
					"strs's length is not equlas checkNames's length");
		
        for (int i = 1; i < o.length; i++) {
        	//student.getmap() 的值为null
            if (isNull(o[i])) {
            	buffer.append(msg[i-1]+",");
            }
        }
        if(buffer.toString().endsWith(",")){
        	buffer.deleteCharAt(buffer.length() - 1);
			buffer.append(" must be specified");
			throw new IllegalArgumentException(buffer.toString());
        }
    }
	
	public static void main(String[] args) throws Exception {		
		Student student=new Student();
		student.setAge(11);
		student.setNameString("");
		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());	
	}

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java 中,使用注解进行参数校验是一种常见的做法。如果需要实现高级写法,可以使用 Hibernate Validator 库中的 ConstraintValidator 接口和自定义注解来实现参数校验。 示例代码如下: 1. 创建自定义注解 ``` @Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = NotEmptyValidator.class) public @interface NotEmpty { String message() default "参数不能为空"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } ``` 在上面的代码中,定义了一个 NotEmpty 注解,用于校验参数非空。其中,@Constraint 注解用于指定校验逻辑的实现类 NotEmptyValidator。 2. 创建校验器 ``` public class NotEmptyValidator implements ConstraintValidator<NotEmpty, Object> { @Override public boolean isValid(Object value, ConstraintValidatorContext context) { if (value == null) { return false; } if (value instanceof String) { return StringUtils.isNotBlank((String) value); } if (value instanceof Collection) { return !((Collection<?>) value).isEmpty(); } if (value instanceof Map) { return !((Map<?, ?>) value).isEmpty(); } if (value.getClass().isArray()) { return Array.getLength(value) > 0; } return true; } } ``` 在上面的代码中,创建了 NotEmptyValidator 类,实现了 ConstraintValidator 接口。isValid 方法用于实现校验逻辑,它可以判断不同类型的参数是否为空。 3. 在接口请求对象中使用注解 ``` public class UserQuery { @NotEmpty(message = "用户名不能为空") private String username; @NotEmpty(message = "角色列表不能为空") private List<Role> roles; // 其他字段略 // getter 和 setter 略 } ``` 在上面的代码中,使用 NotEmpty 注解来标记 username 和 roles 字段,表示它们不能为空。如果校验失败,会抛出异常并返回错误信息。 4. 在 Controller 中进行参数校验 ``` @PostMapping("/users") public ResponseEntity<List<User>> listUsers(@RequestBody @Validated UserQuery query) { List<User> users = userService.listUsers(query); return ResponseEntity.ok(users); } ``` 在上面的代码中,使用 @Validated 注解来开启参数校验功能,并将 UserQuery 对象标记为需要进行校验。如果校验失败,会抛出异常并返回错误信息。 使用上述方法,可以在接口请求对象中使用注解来进行参数校验,而不需要在 Controller 中编写大量的校验代码,从而提高代码可读性和可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值