Simple understanding of annotations

1. Annotation Overview

Brief introduction: Annotations are comments or metadata that are inserted into your code. These annotations can be processed using pre-compilation tools during compilation, or can be processed using the java reflection mechanism during runtime.

Annotation function : 1. Compiler check 2. Define annotation

Annotation advantages: improve development efficiency and low cost

Note shortcomings: large coupling, not conducive to later maintenance

2. Definition of annotations

The annotation is defined by the @interface keyword

Examples:

The use of annotations: the simplest annotation format @Test

Commonly used annotation: @override (indicating the coverage of the parent class method, it should be no stranger!)

3. Meta annotations

Meta annotations are annotations that can be annotated onto annotations. (A basic annotation can be applied to other annotations)

Its role and purpose is to explain other common notes 

There are 5 types of meta tags: @Retention , @Documented , @Target , @Inherited , @Repeatable . (Two of them are more important)

1. @Retention (indicating the survival time of the annotation)

Value: RetentionPolicy.SOURCE The annotation is only reserved in the source code stage, it will be discarded and ignored when the compiler compiles.

           The RetentionPolicy.CLASS annotation is only retained until the compilation is in progress, it will not be loaded into the JVM. 

           RetentionPolicy.RUNTIME annotation can be retained until the program runs, it will be loaded into the JVM,

format:

2. @ Target (specify the application of annotation)

Value: ElementType.ANNOTATION_TYPE can annotate an annotation

           ElementType.CONSTRUCTOR can annotate the constructor

           ElementType.FIELD can annotate attributes

           ElementType.LOCAL_VARIABLE can annotate local variables

           ElementType.METHOD can annotate methods

           ElementType.PACKAGE can annotate a package

           ElementType.PARAMETER can annotate parameters within a method

           ElementType.TYPE can annotate a type, such as class, interface, enumeration 

format:

4. Annotated attributes

Note that there are only member variables and no methods. '

Examples:

use:

V. Annotation extraction

Annotations are obtained through reflection. First, you can determine whether a certain annotation is applied by the isAnnotationPresent () method of the Class object.

This blog is very good for writing comments, I do n’t understand, I recommend you to take a look.

Link: https://blog.csdn.net/briblue/article/details/73824058

 

 

 

 

Published 75 original articles · praised 164 · 110,000 views

Guess you like

Origin blog.csdn.net/qq_41679818/article/details/102077322