JAVA custom annotations (Target, Retention, Documented, Inherit)

Java annotations are some meta-information attached to the code, which are used for parsing and use by some tools during compilation and runtime, and have the functions of description and configuration. Annotations do not and cannot affect the actual logic of the code, but only play a supporting role. Included in the java.lang.annotation package.

1. Meta annotations

Meta-annotations are annotations that refer to annotations. Including @Retention @Target @Document @Inherited four.

1.1, @Retention: Define the retention policy of annotations

@Retention(RetentionPolicy.SOURCE) //Annotations only exist in the source code and are not included in the class bytecode file
@Retention(RetentionPolicy.CLASS) // The default retention policy, annotations will exist in the class bytecode file, but cannot be obtained at runtime,
@Retention(RetentionPolicy.RUNTIME) // The annotation will exist in the class bytecode file and can be obtained by reflection at runtime
1.2, @Target: Define the target of the annotation
The source code of its definition is: 
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
     ElementType[] value();
}
@Target(ElementType.TYPE) // interface, class, enumeration, annotation
@Target(ElementType.METHOD)//方法
@Target(ElementType.FIELD)//Field, enumeration constants
@Target(ElementType.PARAMETER)// method parameters
@Target(ElementType.CONSTRUCTOR) // Constructor
@Target(ElementType.LOCAL_VARIABLE) // local variable
@Target(ElementType.ANNOTATION_TYPE) // 注解
@Target(ElementType.PACKAGE) / // 包
1.3, @Document: indicates that the annotation will be included in the javadoc
1.4, @Inherited: indicates that the subclass can inherit the annotation in the parent class
2. Customization of java annotations
Below is an example of a custom annotation
@Retention ( RetentionPolicy.RUNTIME )
@Target ( ElementType.METHOD )
public @interface ResponseJsonView
{

    /**
     * JSON view name
     * @return
     */
    public Class<? extends View> value();

    /**
     * whether to include properties in the default view
     * @return
     */
    public boolean includeDefaultView() default true;
}
 It can be determined that the annotation is a method annotation through the ElementType enumeration.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326609923&siteId=291194637