import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据验证
* Created by wangshupeng1 on 2016/12/1.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
public @interface DV {
//是否可以为空
boolean nullable() default false;
//最大长度
int maxLength() default 0;
//最小长度
int minLength() default 0;
//参数或者字段描述,这样能够显示友好的异常信息
String description() default "";
//自定义正则验证
String regexExpression() default "";
}
import com.jd.jr.baitiao.quickpay.common.exception.AppRuntimeException;
import com.jd.jr.baitiao.quickpay.common.exception.ExceptionConstants;
import com.jd.jr.baitiao.quickpay.export.vo.DV;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
/**
* Created by wangshupeng1 on 2

本文介绍了如何在Java中使用注解进行数据验证。通过创建一个名为`DV`的注解,包含nullable、maxLength和minLength等属性,实现对字段是否可为空、长度限制等的验证。同时,提供了一个`ValidateService`类,用于遍历对象的字段并执行注解解析,当参数不符合验证规则时抛出异常。示例展示了在Bean上直接添加注解进行参数验证的方法。
最低0.47元/天 解锁文章
4002

被折叠的 条评论
为什么被折叠?



