利用反射、注解校验字段类型
自定义注解
import java.lang.annotation.*;
@Target({ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckNumber {
}
属性添加注解
/* 身高 */
@Column(name = "HEIGHT")
// 校验数据库定义最大长度
@javax.validation.constraints.Size(
groups = {com.anxhit.fw.core.validation.AddGroup.class, com.anxhit.fw.core.validation.UpdGroup.class},
max = 32, message = "height 超过最大长度")
@CheckNumber
private String height;
利用反射判断是否有注解并判断注解的值
public void checkFiledIsNumber(GeneralInspectionPO generalInspectionPO) throws BaseException {
if(generalInspectionPO == null){
return;
}
JSONObject beanJson = JSONObject.fromObject(generalInspectionPO);
Field[] fields = GeneralInspectionPO.class.getDeclaredFields();
for(Field field :fields){
if(field.isAnnotationPresent(CheckNumber.class)){
String fieldJson = underLineToHump(field.getName());
String value = beanJson.getString(fieldJson);
if(StringUtils.isNotBlank(value)){
NumberUtils.checkIsNumberThrowException(value);
}
}
}
}