Pay attention to copyright. If you want to reprint, please attach the author and link
Author: Joshua_yi
Link: https://blog.csdn.net/weixin_44984664/article/details/122088060
1, Annotation
Annotation is also called metadata
(1) Role of annotations
We can analyze the function of annotation from the object of annotation
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Formal parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE, /** * Type parameter declaration * * @since 1.8 */ TYPE_PARAMETER, /** * Use of a type * * @since 1.8 */ TYPE_USE }
- TYPE: annotations can act on classes, interfaces (including other annotations) and enumeration types
- ANNOTATION_TYPE: on other notes
- FIELD: can act on properties of a class
- METHOD: METHOD (excluding construction METHOD)
- CONSTRUCTOR: on the construction method
- PARAMETER: on method parameters
- LOCAL_VARIABLE: on local variables
- PACKAGE: used on packages. For specific usage, please refer to https://blog.csdn.net/weixin_38321868/article/details/118942209
- TYPE_PARAMETER: indicates that the annotation can be written in the declaration statement of type parameters. (eg: generic declaration)
- TYPE_USE: indicates that annotations can be used wherever types are used. Ubiquitous annotations can enable the compiler to perform more strict code inspection, so as to improve the robustness of the program. For example, it can be applied in the following places
- Create object (create with new keyword)
- Type conversion
- Implement the interface using implements
- Throw an exception using the throws declaration
public class Solution { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_PARAMETER) public @interface isParam { } public <@isParam T> void fun1(T ob) { System.out.println(ob); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE) public @interface isNotNull { } public <@isNotNull T> void fun2(@isNotNull T ob) throws @isNotNull Exception { String s = (@isNotNull String) "11111"; System.out.println(ob); } }
Annotations can add some additional information to these program elements, which can be used for later operations.
According to whether an annotation contains member functions, annotations can be roughly divided into two categories
Tag annotations: annotations without member variables are called tags. This Annotation provides us with information only by its own existence, such as @ override.
Metadata Annotation: Annotation containing member variables. Because they can accept more metadata, they are called metadata Annotation. A member is declared as a parameterless method, and its method name and return value define the name and type of the member variable.
PS: Annotation has no member variable, only the member variable of method Annotation is declared in the form of "method without formal parameter" in the Annotation definition, its method name defines the name of the member variable, and its return value defines the type of the member variable.
You can use the default keyword to specify a default value for a member variable
(2) Source code interpretation
Annotation related source code in Java Lang.annotation package
- Annotation is the interface inherited by all annotations, which is why the underlying interface is an interface.
(if @ interface is defined, all annotations will automatically inherit the java.lang.Annotation interface, and cannot inherit other classes or interfaces) - AnnotationFormatError inherits from Error and is thrown when the annotation parser reads the annotation from the class file and determines that there is an Error in the annotation
- Annotationtypemismatch exception inherits from RuntimeException and indicates that the program attempts to access an element of the annotation. The annotation type changes after compilation (or serialization). This exception is thrown at this time
- IncompleteAnnotationException inherits from RuntimeException and indicates that the program attempts to access an element of annotation type. This element is added to the annotation type definition after the annotation is compiled (or serialized), that is, some member variables in the annotation cannot be found.
- ElementType specifies the syntax where annotations may appear in Java programs.
- RetentionPolicy describes the strategy of retaining annotations, including source level, bytecode and runtime
- @Native modifies the class attribute, indicating that this variable can be referenced by local code and is often used by code generation tools.
- The other five annotations can modify other annotations, which are called meta annotations. (Meta-Annotation)
PS: after reading various official documents, I haven't found an accurate definition of this meta annotation.
Annotations that only know that they can act on other annotations are called meta annotations. In order to distinguish it from the meta annotation defined by itself, it is hereinafter collectively referred to as the basic meta annotation
2, Basic meta annotation and annotation parsing
Before explaining the five basic meta annotations, you need to explain ElementType (described earlier) and RetentionPolicy
(1) ElementType
See above
(2) RetentionPolicy
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME }
-
RetentionPolicy.SOURCE: indicates that the annotation will be discarded by the compiler and there will be no annotation information in the bytecode. It is generally used for problems that can be found at the compiler level. For example, @ override is code level visibility, which is combined with the compiler to check problems.
-
RetentionPolicy.CLASS: indicates that the annotation will be written to the bytecode file, which is the default value of @ Retention. In short, its custom annotation parsing needs to implement the process() method of AbstractProcessor. Basic use can refer to this article Compile time annotation of java annotation retentionpolicy Class basic usage
-
RetentionPolicy.RUNTIME: indicates that the annotation will be written to the bytecode file and can be obtained by the JVM at runtime and parsed through reflection.
The functions commonly used for reflection are as follows
- T getAnnotation(Class): get the specified annotation of the current object.
- Annotation[] getAnnotations() X: get all annotations of the current object
- boolean isAnnotationPresent(annotationClass): whether the current object has annotations.
PS: after an annotation is defined, it is only an empty definition, which needs to be given meaning by defining annotation parsing. Common custom annotation parsing is performed through reflection, that is, the annotation Retention to RUNTIME needs to be specified.
(3) @ Documented
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Documented { }
After the API document is generated with javadoc command, the annotation will appear in the document
(4) @ Inherited
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Inherited { }
@Inherited indicates that the annotation is inherited.
That is, if an annotation type decorated with @ Inherited is used for a class, the annotation will be used for the subclass of the class.
(5) @ Retention
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention { /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value(); }
Specifies the annotation lifecycle RetentionPolicy
It has been explained in detail above
(6) @ Target
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */ ElementType[] value(); }
Specifies the annotation action object ElementType
It has been explained in detail above
(7) @ Repeatable
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Repeatable { /** * Indicates the <em>containing annotation type</em> for the * repeatable annotation type. * @return the containing annotation type */ Class<? extends Annotation> value(); }
@Repeatable is jdk1 8 newly added, which means that the same annotation is repeated in the same position. Before this annotation, if you want to use the same annotation on the same type, you need to specify value as an array.
eg:
@FilterPath("/update") @FilterPath("/add") public class A {}
3, Summary
The above part describes the Java annotation in detail combined with the source code. The key point is to explain the annotations, basic meta annotations and related usage scenarios. Many parts only represent their own views. If there are mistakes, please correct them~~
Reference documents
https://blog.csdn.net/chenliguan/article/details/78304025
https://www.jianshu.com/p/613e3b1bd842
https://blog.csdn.net/sjh66655/article/details/112901868
https://blog.csdn.net/xtho62/article/details/113816008
https://blog.csdn.net/u014207606/article/details/52291951