@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNull {
String Message();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NumRange {
int Min();
int Max();
String Message();
}
public class MyValidationUtil {
private static <T> List<String> Validate(T obj){
ArrayList<String> warning = new ArrayList<>();
Class clazz = obj.getClass();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
Field field = null;
try {
field = clazz.getDeclaredField(declaredField.getName());
field.setAccessible(true);
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof IsNull) {
Object o = field.get(obj);
IsNull isNull = (IsNull) annotation;
if (o == null) {
warning.add(isNull.Message());
}
}
if (annotation instanceof NumRange) {
Object o = field.get(obj);
if (o instanceof Integer) {
int value = (Integer) o;
NumRange numRange = (NumRange) annotation;
if (!(value < numRange.Max() && value > numRange.Min())) {
warning.add("错误" + numRange.Message());
}
}
}
}
} catch (NoSuchFieldException | IllegalAccessException ignored) {
}
}
return warning;
}
}
@NumRange(Min = 2,Max=99,Message="vipid为9-99")
private Integer vipId;
@IsNull(Message = "sex不能空")
private Integer sex;
@IsNull(Message = "名字不能空")
private String vipName;