Java annotations are some of the meta-information that is attached to the code, used by some tools to parse and use at compile and run time, to illustrate and configure functionality.
Annotations do not and do not affect the actual logic of the code, only the ancillary role. Included in the Java.lang.annotation package.
1, Yuan annotation
Meta annotations are annotations of annotations. including @Retention @Target @Document @Inherited four kinds.
1.1. @Retention: Define retention policies for annotations
@Retention (Retentionpolicy.source) //annotations only exist in the source code and are not included in the class bytecode file
@Retention (retentionpolicy.class) //default retention policy, annotations exist in the CLASS bytecode file, but are not available at run time .
@Retention (Retentionpolicy.runtime) //annotations are present in the class bytecode file and can be obtained through reflection at run time
1.2. @Target: Define the purpose of the annotations
The source code is defined as:
1 @Documented2 @Retention (retentionpolicy.runtime) 3 @Target (Elementtype.annotation_type) 4 public @interface Target {5 Elementtype[] Value (); 6}
@Target (Elementtype.type) // interfaces, classes, enumerations, annotations
@Target (Elementtype.field) // fields, constants for enumerations
@Target (Elementtype.method) // method
@Target (Elementtype.parameter) // method Parameters
@Target (Elementtype.constructor) // constructor
@Target (elementtype.local_variable)// Local Variables
@Target (Elementtype.annotation_type)// annotations
@Target (elementtype.package)/ // pack
By the above source code can know, his elementtype can have multiple, an annotation can be class, method, field and so on
1.3. @Document: Note that the note will be included in the Javadoc
1.4, @Inherited: The description subclass can inherit this annotation from the parent class
2. Customization of Java annotations
Here is an example of a custom annotation
@Retention (Retentionpolicy.runtime)
The annotation defined is that the annotations exist in the class bytecode file and can be obtained through reflection at run time.
@Target ({Elementtype.type,elementtype.method})
So this annotation can be a class annotation, or it can be an annotation of a method.
Such an annotation is customized, of course, the members of the annotation can be the basic data type, but also for the data, object, and so on
3 The annotations are defined, so how do we get them and parse the annotations?
The reflection mechanism of Java can help, get annotations, the code is as follows: