/**自定义注解*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StringValidator {
/**错误码*/
String code() default "";
/**最小长度*/
int min() default 0;
/**最大长度*/
int max() default 0;
/**是否链接*/
boolean isLink() default false;
}
/**反射校验数据*/
public class ConfigureValidator {
private static Logger logger = LoggerFactory.getLogger(ConfigureValidator.class);
/**校验活动配置*/
public static void validateConfigure( Object object ){
Class cls = object.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
try {
StringValidator annotation = field.getAnnotation(StringValidator.class);
if(annotation == null){
continue;
}
field.setAccessible(true);
Object value = field.get(object);
if(value == null || value.equals("")){
throw XExceptionFactory.create(annotation.code());
}
if(annotation.max() > 0){
if(value.toString().length() > annotation.max()){
throw XExceptionFactory.create(annotation.code());
}
}
} catch (IllegalAccessException e) {
logger.error("基础信息校验出错:",e);
}
}
}
}
/**实体注解*/
public class ConfigureVO implements Serializable{
private static final long serialVersionUID = 3839442265900173771L;
private Integer isEnable = 0;
@StringValidator(code = "MARHET_API_WHEEL_SHARE_003" , max = 20)
@Mapping("shareTitle")
private String title;
@StringValidator(code = "MARHET_API_WHEEL_SHARE_004" , max = 20)
@Mapping("shareDescription")
private String description;
@StringValidator(code = "MARHET_API_WHEEL_LINK_001")
@Mapping("shareUrl")
private String link;
@StringValidator(code = "MARHET_API_WHEEL_URL_001")
@Mapping("shareImageUrl")
private String imageUrl;
}
ConfigureVO share = configure.getShare();
if(share.getIsEnable() == 1){
ConfigureValidator.validateConfigure(share);
}