Custom annotation and its application in reflection

Posted by Piranha on Mon, 03 Jan 2022 17:48:18 +0100

catalogue

1, Annotation (also annotated)

■ comments and meta comments acting on the code:

□ comments applied to the code:

□ meta annotation (annotation applied to other annotations):

□ highlight @ Retention and @ Target:

❀ important application of Annotation: using Annotation in reflection

(1) Annotation on class name:

(2) Annotation on method name:

(3) Annotation on Attribute:

Summary: use of custom annotations

❀ annotation is essentially an abstract class [understand it as so easy for class customization and use]

1. Define an annotation class:

2. Use the annotation ('paste it ') [because the annotation scope of the defined annotation is class, it can only be pasted on class]

3. Get the value of the custom annotation label, that is, call the method in the custom annotation class

1, Annotation (also annotated)

Classes, methods, variables, parameters and packages in Java can be labeled. Unlike Javadoc, Java annotations can obtain annotation content through reflection. (get annotation content by reflection: when the compiler generates class files, annotations can be embedded into bytecode. Java virtual machine can keep annotation content and get annotation content at run time.)

■ annotations include: built-in annotations and custom annotations

Built in annotations: Java defines a set of seven annotations, three of which are in Java Lang, the remaining four are in Java Lang.annotation.

■ comments and meta comments acting on the code:

□ comments applied to the code:

  • @Override - checks whether the method is an overridden method. If it is found that its parent class or the referenced interface does not have this method, a compilation error will be reported.
  • @Deprecated - marks obsolete methods. If this method is used, a compilation warning will be reported.
  • @SuppressWarnings - instructs the compiler to ignore warnings declared in annotations.

□ meta annotation (annotation applied to other annotations):

  • @Retention - identifies how the annotation is saved, whether it is only in the code, incorporated into the class file, or can be accessed through reflection at run time.
  • @Documented - marks whether these annotations are included in the user document.
  • @Target - marks which Java member this annotation should be.
  • @Inherited - marks the annotation class to which the annotation is inherited (the default annotation does not inherit from any subclasses)

□ highlight @ Retention and @ Target:

@Retention: The reserved range of annotation is an enumeration with the following optional values
    RetentionPolicy.SOURCE:Annotations exist in the source file
    RetentionPolicy.CLASS:Annotations exist in the source bytecode file
    RetentionPolicy.RUNTIME:Annotations exist at run time

@Target: Where the annotation appears(For example, on classes, fields, methods, etc),It is also an enumeration with the following optional values
  ElementType.ANNOTATION _ type Applies to annotation types.
  ElementType.CONSTRUCTOR Apply to constructor.
  ElementType.FIELD Apply to a field or property.
  ElementType.LOCAL_VARIABLE Apply to local variables.
  ElementType.METHOD Applies to method level annotations.
  ElementType.PACKAGE Apply to package declaration.
  ElementType.PARAMETER Parameters applied to the method.
  ElementType.TYPE Any element applied to the class.

❀ important application of Annotation: using Annotation in reflection

(1) Annotation on class name:

1):@Annotation name("Annotation value) : If the annotation is on the class name, the class has the information in the annotation  
     @Table("t_student")
     public class Student{
        ......
     }

 2): Then create an annotation:
●Where to post:   @Target(ElementType.Type)
●Save time: @Retention(RetentionPolicy.RUNTIME)
           public @interface Table {
                 String value();   //When @ Table annotation is used: @ Table(value = "t_student");
            }    

 3): (This class has the information in the annotation) use reflection to obtain annotation information:
     //Create annotation object: get the annotation object on the Student class
  ① Create annotation object       Table table = Student class.getAnnotation(Table.class);
  ② Call the method of the annotation object  String tableName =table.value();

(2) Annotation on method name:

    1)student Methods in classes test Note on:    
    @MyAnnotation(value = "123",name = "lisi")
    public static void test(){
        ......
     }

    2)Then create an annotation:
    ●Where to post:  @Target(ElementType.Type)
    ●Save time:@Retention(RetentionPolicy.RUNTIME)
              public @interface MyAnnotation {
                    String value() default "abc";
                    String name() default "zhangsan";
              }

    3)(The method of this class has the information in the annotation) use reflection to obtain annotation information:
         Class clazz = Class.forName("Student Path of");
         Method[] ms = clazz.getMethods();
         for (Method m : ms) {
            if(m.isAnnotationPresent(MyAnnotation.class)){
              //Create annotation object: get the annotation object on the test method; And call the method of the annotation object
                String value = m.getAnnotation(MyAnnotation.class).value();
           String name = m.getAnnotation(MyAnnotation.class).name();
            }
        }

(3) Annotation on Attribute:

 1)student Properties in class id Note on:
    @Sid(min = 6,max = 10)
     private int id;
 2)Then create an annotation:
    ●Where to post:  @Target(ElementType.Type)
    ●Save time:@Retention(RetentionPolicy.RUNTIME)
              public @interface Sid{
                 int min() default 1;
                 int max() default 10;
             }
 3)(The attribute of this class has the information in the annotation) use reflection to obtain annotation information:
       Class clazz = Class.forName("Student Path of");
       Field[] fs = clazz.getDeclaredFields();
       for (Field f: fs){
            //Create annotation object: get @ Sid annotation on attribute
            Sid id = f.getAnnotation(Test.class); 
            if(id != null){
                f.setAccessible(true);//Set properties accessible 
              //Call the method of the annotation object
                   int min = id.min();
                  int max = id.max();
                }
        }

Summary: use of custom annotations

❀ annotation is essentially an abstract class [understand it as so easy for class customization and use]

1. Define an annotation class:

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME)
 public @interface Table{
 	String value();
 } 

● @ Target(ElementType.TYPE) is a meta annotation, indicating a custom annotation class. The scope of Table annotation is TYPE class.

● @ Retention(RetentionPolicy.RUNTIME) is also a meta annotation, indicating that the custom annotation class Table annotation takes effect when RUNTIME is running.

2. Use the annotation ('paste it ') [because the annotation scope of the defined annotation is class, it can only be pasted on class]

 @Table("t_stu") //It should have been written as @ Table(value="t_stu"), because the custom annotation class has only one method, abbreviated as
 public class Student{
 
 }


//===============================================================================

//There are several methods in the custom annotation, such as:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME)
 public @interface Table{
 	String value();
    String name();
 } 


//Label
 @Table(value="fupo" name="xiaoming")  
 public class Student{
     
 }

3. Get the value of the custom annotation label, that is, call the method in the custom annotation class

● create a user-defined annotation object and call the method with the user-defined annotation object

//Get the value in the annotation label:

//(1) Create the annotation object first 
Table table = classType.getAnnotation(Table.class);
//Because the annotation is on the class Getannotation (annotation label class))
//If annotation is in attribute, use attribute Getannotation (annotation class) 

//(2) Call the method defined in the annotation label class to obtain the value passed in the annotation label 
String tableName = table.value();

Topics: Java reflection Annotation