Introduction: This two days to look at the content of Java custom annotations, and then according to my own understanding to write two pieces of code, is quite interesting, this article includes three parts: annotation foundation, through annotations to assign values (combined with the factory method pattern), through annotations to verify.
First, the basis of annotations
1. Definition of annotations: A Java file is called an Annotation and is represented by @interface.
2. Meta annotations: Annotate some things on @interface as required, including @Retention, @target, @Document, and @Inherited.
3. Retention strategy of annotations:
@Retention(retentionPolicy.source) // Annotations exist only in the SOURCE code and are not included in class bytecode files
@Retention(retentionPolicy.class) // Default Retention policy. Annotations are present in CLASS bytecode files but not available at runtime
@Retention(retentionPolicy.runtime) // Annotations are stored in class bytecode files and can be retrieved by reflection at RUNTIME
4. Purpose of annotations:
@target (elementType.type) // Interface, class, enumeration, annotation
@target (elementType.field) // Constants for fields and enumerations
@ Target (ElementType. METHOD) / / METHOD
@target (elementtype.parameter) // Method PARAMETER
@target (elementtype.constructor) // CONSTRUCTOR
@target (elementType.local_variable) // Local variable
@ Target (ElementType ANNOTATION_TYPE) / / annotation
@ Target (ElementType. PACKAGE) / / PACKAGE
5. Annotations are included in Javadoc:
@Documented
6. Annotations can be inherited:
@Inherited
Annotation parser: Used to parse custom annotations.
Assignment via annotation (combined with factory method pattern)
1. Custom annotations
package annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Inherited
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Init
{
public String value() default "";
}
Copy the code
2. Use annotations in the data model
package model; import annotation.Init; public class User { private String name; private String age; public String getName() { return name; } @Init(value = "liang") public void setName(String name) { this.name = name; } public String getAge() { return age; } @Init(value = "23") public void setAge(String age) { this.age = age; }}Copy the code
3. Use the Construct Factory as the Annotation Parser
package factory; import java.lang.reflect.Method; import annotation.Init; import model.User; public class UserFactory { public static User create() { User user = new User(); [] methods = user.class.getMethods (); try { for (Method method : {// If this method has annotations, The annotation data to assign values to the user object inside the if (method. IsAnnotationPresent (Init. Class)) {Init Init = method. The getAnnotation (Init. Class); method.invoke(user, init.value()); } } } catch (Exception e) { e.printStackTrace(); return null; } return user; }}Copy the code
4. Running code
package app; import java.lang.reflect.InvocationTargetException; import factory.UserFactory; import model.User; public class Test { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { User user = UserFactory.create(); System.out.println(user.getName()); System.out.println(user.getAge()); }}Copy the code
5. Running result
liang 23
Third, verify by annotation
1. Custom annotations
package annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Inherited
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Validate
{
public int min() default 1;
public int max() default 10;
public boolean isNotNull() default true;
}
Copy the code
2. Use annotations in the data model
package model; import annotation.Validate; public class User { @Validate(min = 2, max = 5) private String name; @Validate(isNotNull = false) private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}Copy the code
3. Annotation parser
package check; import java.lang.reflect.Field; import annotation.Validate; import model.User; Public class UserCheck {public static Boolean check(User User) {if (User == null) {system.out.println ("!! Check object is empty!!" ); return false; } / / get all the attributes of the User class (if you use the getFields, cannot access to the private property) Field [] fields = User. The class. The getDeclaredFields (); for (Field field : Fields) {// If the attribute is annotated, Check the if (field. IsAnnotationPresent (Validate. Class)) {Validate the Validate = field. The getAnnotation (Validate. Class); If (field-getName ().equals("age")) {if (user.getage () == null) {if (validate.isnotnull ()) {system.out.println ("!! Age null check not pass: not null!!" ); return false; } else {system.out. println(" age can be null: can be null "); continue; }} else {system.out.println (" age can be null check "); } if (user.getage ().length() < validate.min()) {system.out.println ("!! Age minimum length check failed!!" ); return false; } else {system.out.println (" age minimum length check passed "); } if (user.getage ().length() > validate.max()) {system.out.println ("!! Age maximum length check failed!!" ); return false; } else {system.out.println (" age maximum length check "); } } if (field.getName().equals("name")) { if (user.getName() == null) { if (validate.isNotNull()) { System. Out.println ("!!!!! Name null check failed: not null!!" ); return false; } else {system.out.println (" name can be null: can be null "); continue; }} else {system.out.println (" name can be null check "); } if (user.getName().length() < validate.min()) {system.out.println ("!! Name minimum length verification failed!!" ); return false; } else {system.out.println (" name minimum length check "); } if (user.getName().length() > validate.max()) {system.out.println ("!! Name Max length check failed!!" ); return false; } else {system.out.println (" name Max length check "); } } } } return true; }}Copy the code
4. Running code
package app; import check.UserCheck; import model.User; public class Test { public static void main(String[] args) { User user = new User(); user.setName("liang"); user.setAge("1"); System.out.println(UserCheck.check(user)); }}Copy the code
5. Running result
Name Null Verification By Name Minimum Length Verification by Name Maximum Length Verification by Age Null Verification by Name Minimum Length Verification by Age Maximum length verification trueCopy the code