Java. Lang. annotation. Retention indicates how the Compilation Program treats the annotation when customizing annotation. By default, the Compilation Program will keep the annotation information in the. Class file, but will not be read by the virtual machine. It is only used to provide information when the Compilation Program or tool is running.
Note: When using retention, you must provide a retentionpolicy Enumeration type parameter.
Retentionpolicy has three enumeration types:
- Source, // compile the program to complete the task after processing the annotation information
- Class, // The Compiler stores annotation in the class file. The default value is
- Runtime // The Compilation Program stores annotation in class notation and can be read by the VM (via reflection mechanism ). This function is very powerful in combination with reflection.
Example:
Step 1: Create an annotation named myannotation. java. Note that the retention and retentionpolicy packages are introduced.
Package test;
Import java. Lang. annotation. retention;
Import java. Lang. annotation. retentionpolicy;
@ Retention (retentionpolicy. runtime)
Public @ interface myannotation {
String Hello () Default "sunqitang ";
String world ();
}
Step 2: Create a mytest. Java to use the above annotation.
Public class mytest {
@ Myannotation (World = "Hello, world! ", Hello =" Hello, Beijing! ")
Public void output (){
System. Out. println ("output is running ");
}
}
Step 3: Use the reflection mechanism to call the content in the Annotation
Import java. Lang. annotation. annotation;
Import java. Lang. Reflect. method;
Public class myreflection {
Public static void main (string [] ARGs) throws exception {
Class <mytest> C = mytest. Class; // obtain the class to be called
Method method = C. getmethod ("output", new class [] {}); // obtain the method to be called. Output indicates the name of the method to be called, new Class [] {} is the required parameter. This method is used because it is null.
If (method. isannotationpresent (myannotation. Class) {// whether there is an annotation of the type myannotation
Myannotation annotation = method. getannotation (myannotation. Class); // obtain the Annotation
System. Out. println (annotation. Hello (); // call the annotation content
System. Out. println (annotation. World (); // call the annotation content
}
System. Out. println ("------------------------");
Annotation [] annotations = method. getannotations (); // obtain all annotations. It must be of the runtime type.
For (annotation: Annotations) {// traverse the name of the Annotation
System. Out. println (annotation. annotationtype (). getname ());
}
}
}
Running result:
Hello, Beijing!
Hello, world!
------------------------
Test. myannotation
@ Retention Note