This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
1. Background
In her recent study, Lele found that others had their own definition of annotations, which she thought was very cool. Annotation is a kind of aspect, and it must be cool to realize it by herself, so Lele also wrote a custom annotation for email verification
The second practice
-
Write an email verification note first
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface EmailValidate { String message(); } Copy the code
-
Write an annotation manager
public class EmailValidateHandle { public static <T> String validator(T t) throws IllegalArgumentException, IllegalAccessException{ StringBuilder errorMessage = new StringBuilder(); Class<? extends Object> cla = t.getClass(); Field[] fields = cla.getDeclaredFields(); Field[] fields = cla.getDeclaredFields(); EmailValidate emailValidateAnnotation = f.getAnnotation(emailvalidate.class); for(Field f:fields){ if(null ! = emailValidateAnnotation){// Set some properties to be accessible. F.setaccessible (true); Object val = f.et (t); boolean flag = checkEmail(val); if(! Flag) {/ / comment on the abnormal information errorMessage. Append (emailValidateAnnotation. Message ()), append (", "); } } } return errorMessage.toString(); }}Copy the code
-
Place the annotation on the property to validate
/** * Recipient */ @emailValidate (message = "recipient email format is incorrect ") private String recipients; /** * @emailValidate (message = "ccEmail ") public String ccEmail;Copy the code
-
Call it where it is needed
String validator = EmailValidateHandle.validator(object); Copy the code
5. Custom annotations complete!