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); } }
}
|