注解类
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface Validate {
public Class> type() default String.class;
}
Util类
public static String validate(Object param) {
for (Field f : param.getClass().getDeclaredFields()) {
if (f.isAnnotationPresent(Validate.class)) {
Validate v = f.getAnnotation(Validate.class);
Class> type = v.type();
f.setAccessible(true);
Object obj = null;
try {
obj = f.get(param);
} catch (IllegalArgumentException e) {
LOG.error("注解异常",e);
} catch (IllegalAccessException e) {
LOG.error("注解异常",e);
}
if(obj==null)
return f.getName()+"不能为空";
if(StringUtils.isBlank(obj.toString()))
return f.getName()+"不能为空";
String vType = type.getName();
if("String".equals(type))
continue;
String val = obj.toString();
boolean bool = false;
try {
if("java.lang.Integer".equals(vType)){
Integer.parseInt(val);
}else if("java.lang.Long".equals(vType)){
Long.parseLong(val);
}else if("java.lang.Byte".equals(vType)){
Byte.parseByte(val);
}
} catch (NumberFormatException e) {
bool = true;
}
if(bool){
return f.getName()+"类型不正确";
}
}
}
return null;
}