Annotation and its function in java

1. What are java annotations

Annotation, as the name suggests, is to add notes to something, which will store some information, which may be very useful for a certain period of time in the future.
Java annotation is also called Java annotation. Java provides a set of mechanism, which enables us to add annotations (i.e. attach some information) to packages, classes, methods, fields, parameters, variables, etc., and extract the annotated information for use through reflection at a later time.

2. Accessing annotations through reflection

After the program obtains the object of a class through reflection, the program can call the following four methods of the object to access the annotation information:

  • Method 1: t getannotation (class annotation class): returns the annotation of the specified type that exists on the program element. If the annotation of this type does not exist, it returns null
  • Method 2: Annotation[] getAnnotations(): returns all annotations that exist on the program element
  • Method 3: Boolean is annotationpresent (class <? Extends annotation > annotationclass): judge whether the program element contains annotations of the specified type. If it exists, return true; Otherwise, false is returned
  • Method 4: annotation [] getdeclaraedannotations(): returns all annotations that exist directly on this element. Unlike other methods, this method ignores inherited comments. If no annotation exists directly on this element, an array with a length of zero is returned. The caller of this method can modify the returned array at will, but this will not have any impact on the arrays returned by other callers.

3. Custom Java annotations

3.1 why should I customize annotations

Java has three built-in annotations since version 1.5 by default:

  • @Override: it can only be used on methods to tell others that this method overrides the parent class
  • @Deprecated: it is recommended that others do not use it when using the old API. A warning message will be generated when compiling, which can be set on all elements in the program
  • @SuppressWarnings: this type can temporarily turn off some warning messages

However, these three annotations alone can not meet some of our development needs. So java allows us to use custom annotations.

3.2 how to customize annotations

The customization steps are roughly divided into two steps:

  • Use the @ interface keyword (note, not interface, but @ interface) to declare the annotation name, as well as the annotation member attribute or parameter called annotation
  • Use the four built-in meta annotations in java to limit the function and scope of custom annotations

3.3 what is meta annotation

Meta annotations are annotations that define annotations, that is, the role of these meta annotations is to restrict other annotations. Please distinguish the above three annotations. They are also defined through meta annotations. Meta annotations mainly have four @ Target,@Retention,@Documented,@Inherited

Meta notes include:@Target,@Retention,@Documented,@Inherited 

@Target Indicates where the annotation is used, possibly ElemenetType Parameters include: 
	ElemenetType.CONSTRUCTOR Constructor declaration 
	ElemenetType.FIELD Domain declaration (including enum (example) 
	ElemenetType.LOCAL_VARIABLE Local variable declaration 
	ElemenetType.METHOD Method declaration 
	ElemenetType.PACKAGE Package declaration 
	ElemenetType.PARAMETER Parameter declaration 
	ElemenetType.TYPE Class, interface (including annotation type) or enum statement 
 
@Retention Indicates the level at which the annotation information is saved. Optional RetentionPolicy Parameters include: 
	RetentionPolicy.SOURCE Annotations will be discarded by the compiler 
	RetentionPolicy.CLASS Annotation in class Available in the file, but will be deleted VM discard 
	RetentionPolicy.RUNTIME VM Annotations will also be retained at run time, so the information of annotations can be read through the reflection mechanism. 
 
@Documented Include this annotation in javadoc in 
 
@Inherited Allow subclasses to inherit annotations from parent classes 

3.4 examples of customization and annotation usage

  • File structure:

  • Customize a class level annotation Description

package annotation_;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)//This annotation applies to classes
@Retention(RetentionPolicy.RUNTIME)//Annotations are retained until run time
@Documented	//Include this annotation in javadoc
public @interface Description{
    String value();
}
  • Define another method level annotation Name
package annotation_;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//Note that @ Target here is different from the parameter member in @ Description
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name{
   String originate();
   String community();
}
  • Then use the above two annotations
package annotation_;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Description(value="javaeye,Make the best software development communication community")
public class JavaEyer {
      @Name(originate="founder:robbin",community="javaEye")
      public String getName()
      {
                return null;
      }
     
      @Name(originate="founder:Jiangnan white clothes",community="springside")
      public String getName2()
      {
                return "Borrow two id One use,Write this example,Excuse me!";
      }
}

Note: the annotation "@ Description(value =" javaeye, make the best software development communication community ")" can be written as "@ Description(" javaeye, make the best software development communication community ")". The results of these two methods are the same. Because the parameter (or attribute) of the Description annotation is value when it is defined, and value is special, it can be written out without displaying when it is specified. Of course, if the defined parameter name is not value but other, such as des, then when using annotation, you must explicitly write out the parameter name and then assign a value: @ Description(Des = "xxx")

  • Extract annotation information
package annotation_;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

public class TestAnnotation {
        /**
         * author lighter
         * Note: please refer to the javaDoc document for the usage of the API related to Annotation
         */
      public static void main(String[] args) throws Exception {
      String CLASS_NAME = "annotation_.JavaEyer";
      Class test = Class.forName(CLASS_NAME);
      
      boolean flag = test.isAnnotationPresent(Description.class);
       if(flag)
       {
                Description des = (Description)test.getAnnotation(Description.class);
                System.out.println("describe:"+des.value());
                System.out.println("-----------------");
       }
      
       Method[] method = test.getMethods();
       //Save all methods using @ Name in JavaEyer class to Set
       Set<Method> set = new HashSet<Method>();
       for(int i=0;i<method.length;i++)
       {
                boolean otherFlag = method[i].isAnnotationPresent(Name.class);
                if(otherFlag) set.add(method[i]);
       }
       for(Method m: set)
       {
                Name name = m.getAnnotation(Name.class);
                System.out.println(name.originate());
                System.out.println("Community created:"+name.community());
       }
    }
}

Note: all customized annotations (such as Description and Name) will automatically inherit Java Lang. Annotation is an interface, so you can't inherit other classes or interfaces. The most important point is the parameter setting in Annotation type:

  • First, it can only be decorated with public or default access rights, such as String value(), which is set as the default type of defaultaul
  • Second, parameter members can only use eight basic data types: byte, short, char, int, long, float, double and Boolean, and data types such as String, enum, class and annotations, as well as arrays of these types, such as String value(), where the parameter type is String
  • The operation results are as follows:

Custom notes and usage examples

/***********Annotation statement***************/

/**
 * Fruit name annotation
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
    String value() default "";
}

/**
 * Fruit color notes
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    /**
     * Color enumeration
     * @author peida
     *
     */
    public enum Color{ BULE,RED,GREEN};
    
    /**
     * color property
     * @return
     */
    Color fruitColor() default Color.GREEN;

}

/**
 * Fruit supplier notes
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
    /**
     * Supplier number
     * @return
     */
    public int id() default -1;
    
    /**
     * Supplier name
     * @return
     */
    public String name() default "";
    
    /**
     * Supplier address
     * @return
     */
    public String address() default "";
}

/***********Annotation use***************/

public class Apple {
    
    @FruitName("Apple")
    private String appleName;
    
    @FruitColor(fruitColor=Color.RED)
    private String appleColor;
    
    @FruitProvider(id=1,name="Shaanxi hongfuji group",address="Hongfuji building, 89 Yan'an Road, Xi'an, Shaanxi")
    private String appleProvider;
    
    public void setAppleColor(String appleColor) {
        this.appleColor = appleColor;
    }
    public String getAppleColor() {
        return appleColor;
    }
    
    public void setAppleName(String appleName) {
        this.appleName = appleName;
    }
    public String getAppleName() {
        return appleName;
    }
    
    public void setAppleProvider(String appleProvider) {
        this.appleProvider = appleProvider;
    }
    public String getAppleProvider() {
        return appleProvider;
    }
    
    public void displayName(){
        System.out.println("The name of the fruit is apple");
    }
}

/***********Annotation processor***************/

public class FruitInfoUtil {
    public static void getFruitInfo(Class<?> clazz){
        
        String strFruitName=" Fruit Name:";
        String strFruitColor=" Fruit color:";
        String strFruitProvicer="Supplier information:";
        
        Field[] fields = clazz.getDeclaredFields();
        
        for(Field field :fields){
            if(field.isAnnotationPresent(FruitName.class)){
                FruitName fruitName = (FruitName) field.getAnnotation(FruitName.class);
                strFruitName=strFruitName+fruitName.value();
                System.out.println(strFruitName);
            }
            else if(field.isAnnotationPresent(FruitColor.class)){
                FruitColor fruitColor= (FruitColor) field.getAnnotation(FruitColor.class);
                strFruitColor=strFruitColor+fruitColor.fruitColor().toString();
                System.out.println(strFruitColor);
            }
            else if(field.isAnnotationPresent(FruitProvider.class)){
                FruitProvider fruitProvider= (FruitProvider) field.getAnnotation(FruitProvider.class);
                strFruitProvicer=" Supplier No.:"+fruitProvider.id()+" Supplier Name:"+fruitProvider.name()+" Supplier address:"+fruitProvider.address();
                System.out.println(strFruitProvicer);
            }
        }
    }
}

/***********Output results***************/
public class FruitRun {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        FruitInfoUtil.getFruitInfo(Apple.class);
        
    }

}

====================================
 Fruit Name: Apple
 Fruit color: RED
 Supplier No.: 1 supplier name: Shaanxi hongfuji group supplier address: hongfuji building, No. 89 Yan'an Road, Xi'an, Shaanxi

reference resources: https://blog.csdn.net/liukai6/article/details/89854903
reference resources: https://www.cnblogs.com/peida/archive/2013/04/26/3038503.html

Keywords: Java

Added by stuartshields on Thu, 17 Feb 2022 23:55:16 +0200