Check工具类

2020-06-15

直接上代码

定义Check注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* @author : sungm
* @since : 2020-06-15
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {

boolean notNull() default false;

boolean notEmpty() default false;

boolean notBlank() default false;

String regex() default "";

}

校验工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import demo.annotations.Check;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.regex.Pattern;

/**
* @author : sungm
* @since : 2020-06-15 16:01
*/
public class CheckUtils {

private static final String EMPTY = "";

public static <T> void check(T t) throws Exception {
Class clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
if (fields.length == 0) {
return;
}
for (Field field : fields) {
field.setAccessible(true);
check(field.get(t), field);
}
}

private static void check(Object value, Field field) throws Exception {
Check check = field.getAnnotation(Check.class);
if (Objects.isNull(check)) {
return;
}

if (check.notNull() && Objects.isNull(value)) {
throw new Exception("Field (" + field.getName() + ") cannot be null.");
}
if (check.notEmpty() && (Objects.isNull(value) || EMPTY.equals(value.toString()))) {
throw new Exception("Field (" + field.getName() + ") cannot be empty.");
}
if (check.notBlank() && (Objects.isNull(value) || EMPTY.equals(value.toString().trim()))) {
throw new Exception("Field (" + field.getName() + ") cannot be blank.");
}
checkRegex(field, value, check.regex());
}

private static void checkRegex(Field field, Object value, String regex) throws Exception {
if (EMPTY.equals(regex) || Objects.isNull(value)) {
return;
}

if (!Pattern.matches(regex, value.toString())) {
throw new Exception("Wrong data format : Field (" + field.getName() + "), value is : " + " value" + ", regex is : " + regex);
}
}

}

DTO 数据传输层

1
2
3
4
5
6
7
8
9
10
11
12
13
public class PersonDto {

@Check(notBlank = true)
private String name;
@Check(notNull = true, regex = "\\d\\d")
private Integer age;
@Check(notBlank = true, regex = "男|女")
private String sex;
private String idCard;
private String accessNumber;

//省略了getter、setter方法
}

程序入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

/**
* @author : sungm
* @since : 2020-06-15 17:50
*/
public class Main {

public static void main(String[] args) throws Exception {
PersonDto personDto = new PersonDto();
personDto.setIdCard("0001");
personDto.setName("孙广明");
personDto.setSex("男");
personDto.setAge(25);
CheckUtils.check(personDto);
}
}