1. Understand annotations
We need to make a simple learning on the Annotation technology added to JDK 5.0, because Spring supports @ AspectJ, and @ AspectJ itself is based on the Annotation Technology of JDK 5.0. So learning the annotation knowledge of JDK 5.0 helps us better understand and master Spring's AOP technology.
For Java developers, apart from the source code, we also use the Javadoc tag to comment out classes, methods, or member variables, this allows you to use the Javadoc tool to generate the Javadoc documentation that matches the source code. These Javadoc labels, such as @ param and @ return, are annotation labels, which provide comments Describing program code for third-party tools. Friends who have used Xdoclet will be more touched by this. For example, Struts and Hibernate all provide Xdoclet labels, which can be used to quickly generate configuration files for the corresponding program code.
The JDK5.0 annotation can be seen as an extension and development of Javadoc labels and Xdoclet labels. In JDK5.0, We can customize these labels and obtain annotation in the class through the reflection mechanism of the Java language to complete specific functions.
Annotation is the ancillary information of the code. It follows a basic principle: annotation cannot directly interfere with the running of the program code. No matter how annotations are added or deleted, the code can run normally. The Java interpreter ignores these annotations, and a third-party tool processes the annotations. Third-party tools can use the annotations in the code to indirectly control the running of program code. They read the annotation information through the Java reflection mechanism and modify the logic of the target program according to the information, this is exactly the method Spring AOP uses to support @ AspectJ.
The annotation syntax is relatively simple. Besides the use of the @ symbol, it is basically consistent with the inherent Syntax of java. java has three built-in annotations, which are defined in the java. lang package.
@ Override: it can only be used on methods. It is used to tell others that this method is used to rewrite the parent class.
@ Deprecated: It is recommended that you do not use the old APIs. Warnings are generated during compilation and can be set to all elements in the program.
@ SuppressWarnings: Indicates disabling improper compiler warning information.
2. Define annotations
The following is an example of defining annotations.
@ Target (ElementType. TYPE)
@ Retention (RetentionPolicy. RUNTIME)
@ Brief ented
@ Inherited
Public @ interface Description {
String value ();
}
@ Interface is a keyword. When designing annotations, you must define a type as @ interface instead of class or interface keywords. All annotation classes are implicitly inherited from java. lang. Annotation. annotation. Annotations cannot be explicitly inherited from other interfaces.
An Annotation can have multiple members. The member declaration is similar to the interface method declaration. Here, we define only one member. The member declaration has the following restrictions:
A) a member is declared in the form of no input parameter and no Exception thrown, such as boolean value (String str) and boolean value () throws Exception;
B) You can use default to specify a default value for the member. For example, String level () default "LOW_LEVEL" and int high () default 2 are valid. Of course, you can also leave the default value unspecified;
C) The member types are restricted. Valid types include the original type and its encapsulation Class, String, Class, enums, annotation type, and the array type of the preceding types. For example, ForumService value () and List foo () are invalid.
D) if the annotation has only one member, the member name must be named value (). during use, the member name and value assignment number (=) can be ignored ), for example, @ Description ("example using annotation "). When the annotation class has multiple members, if you only assign values to the value members, you do not need to use the value assignment number. If you assign values to multiple members at the same time, you must use the value assignment number, for example, @ DeclareParents (value = "NaiveWaiter", defaultImpl = SmartSeller. class ).
E) The annotation class can have no members, and the annotation without members is called the identity annotation. The Interpreter processes the existence or absence of the annotation accordingly;
The annotation definition contains four meta Annotations: @ Target, @ Retention, @ incluented, and @ Inherited. The functions of each element annotation are as follows:
1) @ Target
Indicates where the annotation is used. Possible ElemenetType parameters include:
Ø ElemenetType. CONSTRUCTOR declaration.
Ø ElemenetType. FIELD Declaration (including enum instances ).
Ø ElemenetType. LOCAL_VARIABLE local variable declaration.
Ø ElemenetType. METHOD declaration.
Ø ElemenetType. PACKAGE declaration.
Ø ElemenetType. PARAMETER declaration.
ElemenetType. TYPE class, interface (including annotation TYPE) or enum declaration.
2) @ Retention
Indicates the level at which the annotation information is saved. Optional RetentionPolicy parameters include:
The RetentionPolicy. SOURCE annotation will be discarded by the compiler.
The RetentionPolicy. CLASS annotation is available in the class file, but is discarded by the VM.
Ø RetentionPolicy. runtime vm will retain annotations during RUNTIME, so the annotation information can be read through reflection mechanism.
For example, if the Retention in @ Override is set to SOURCE, the Retention in @ Deprecated is set to RUNTIME after compilation is successful, in addition to warning which Deprecated method is used during compilation, you can check whether the method is Deprecated during execution.
3) @ brief ented
Include this annotation in javadoc
4) @ Inherited
Allow subclass to inherit the annotation in the parent class
3. Use annotations
The following is an example of using annotation.
@ Description (value = "example using annotation ")
Public class TestAnnotation {
}
Use annotation Syntax: @ <annotation Name> (<member name 1 >=< member value 1>, <member name 1 >=< member value 1> ,...)
If the Members are of the array type, you can assign values through {}. For example, the members of the boolean array can be set to {true, false, true }. The following is an example of annotation:
1) multi-member Annotation
@ AnnoExample (id = 2868724, synopsis = "Enable time-travel", engineer = "Mr. Peabody ")
2) annotation of a member, whose name is value
Member names and values can be omitted: @ Copyright ("Right Reserved ")
@ Copyright ("2011 bookegou.com All Right Reserved ")
3) member-less Annotation
@ Override
@ Override
4) member is the annotation of the string array
@ SuppressWarnings (value = {"unchecked", "fallthrough "})
@ SuppressWarnings (value = {"unchecked", "fallthrough "})
5) The member is an annotation of the annotation array type.
@ Reviews ({@ Review (grade = Review. Grade. EXCELLENT, reviewer = "df "),
@ Review (grade = Review. Grade. UNSATISFACTORY, reviewer = "eg ",
Comment = "This method needs an @ Override annotation ")})
@ Reviews ({@ Review (grade = Review. Grade. EXCELLENT, reviewer = "df "),
@ Review (grade = Review. Grade. UNSATISFACTORY, reviewer = "eg ",
Comment = "This method needs an @ Override annotation ")})
The @ Reviews annotation has a member of The @ Review annotation array type. The @ Review annotation type has three members. The reviewer and comment are both of the String type, but the comment has the default value, grade is a member of the enumeration type.
4. parse Annotation
The following is an example of parsing annotation.
Public class ParseAnnotation {
Public static void main (String [] args) throws Exception {
Final Class cls = Class. forName ("com. annotation. TestAnnotation ");
Final Method [] method = cls. getMethods ();
// Determine whether there are annotations of the specified annotation type
If (cls. isAnnotationPresent (Description. class )){
// Return the annotation of the specified type based on the annotation type
Description des = (Description) cls. getAnnotation (Description. class );
System. out. println ("annotation Description:" + des. value ());
}
}
}
The output result is as follows:
Annotation Description: An Example Using Annotation
As mentioned above, Annotations do not directly affect the running of programs, but third-party programs or tools can use annotations in code to perform special tasks and indirectly control the running of programs. For the RetentionPolicy. RUNTIME retention period annotation, we can use the annotation in the reflection mechanism annotation class.
In JDK5.0, the methods for accessing Annotation information are added to reflection objects such as Package, Class, Constructor, Method, and Field: <T extends Annotation> T getAnnotation (Class <T> annotationClass ), this method supports direct return of annotation objects through generics.