Java annotations are some meta information appended to the code. They are used for parsing and using some tools during compilation and runtime to provide instructions and configuration functions.
Annotations do not and cannot affect the actual logic of the Code. They only play an auxiliary role. Included in the java. lang. annotation package.
1. Metadata Annotation
Meta annotation refers to the annotation of the annotation. There are four types: @ Retention @ Target @ Document @ Inherited.
1.1 @ Retention: defines the annotation Retention policy
Java code
@ Retention (RetentionPolicy. SOURCE) // The annotation only exists in the SOURCE code and is not included in the class bytecode file.
@ Retention (RetentionPolicy. CLASS) // The default Retention policy. The annotation 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 through reflection during RUNTIME.
1.2 @ Target: define the Target of the Annotation
Java code
@ Target (ElementType. TYPE) // interface, class, enumeration, Annotation
@ Target (ElementType. FIELD) // constant of the FIELD and enumeration
@ Target (ElementType. METHOD) // METHOD
@ Target (ElementType. PARAMETER) // method PARAMETER
@ Target (ElementType. CONSTRUCTOR) // CONSTRUCTOR
@ Target (ElementType. LOCAL_VARIABLE) // local variable
@ Target (ElementType. ANNOTATION_TYPE) // Annotation
@ Target (ElementType. PACKAGE) // PACKAGE
There can be multiple elementtypes, and one annotation can be class, method, and field.
1.3 @ Document: indicates that the annotation will be included in javadoc.
1.4 @ Inherited: indicates that the subclass can inherit the annotation in the parent class.
The following is an example of custom annotation.
2. annotation Customization
Java code www.2cto.com
@ Retention (RetentionPolicy. RUNTIME)
@ Target (ElementType. METHOD)
Public @ interface HelloWorld {
Public String name () default "";
}
3. Use of annotations and test classes
Java code
Public class SayHello {
@ HelloWorld (name = "James ")
Public void sayHello (String name ){
System. out. println (name + "say hello world! ");
} // Www.heatpress123.net
}
4. parse Annotation
The reflection mechanism of java can help to get annotations. The Code is as follows:
Java code
Public class AnnTest {
Public void parseMethod (Class <?> Clazz ){
Object obj;
Try {
// Create a new object using the default constructor
Obj = clazz. getConstructor (new Class [] {}). newInstance (
New Object [] {});
For (Method method: clazz. getDeclaredMethods ()){
HelloWorld say = method. getAnnotation (HelloWorld. class );
String name = "";
If (say! = Null ){
Name = say. name ();
System. out. println (name );
Method. invoke (obj, name );
}
}
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public static void main (String [] args ){
AnnTest t = new AnnTest ();
T. parseMethod (SayHello. class );
}
}