Java annotations are some of the meta information attached to the code, which is used to parse and use some tools as they compile, run, and function as a description and configuration.
Annotations do not and will not affect the actual logic of the code, only to play a supporting role. Included in the Java.lang.annotation package.
1, meta-annotation
A meta annotation is an annotation of an annotation. including @Retention @Target @Document @Inherited four species.
1.1, @Retention: Define the retention policy of annotations
Java code
Copy Code code as follows:
@Retention (Retentionpolicy.source)//annotations exist only in the source code and are not included in the class byte code file
@Retention (Retentionpolicy.class)//default retention policy, annotations exist in the CLASS bytecode file but cannot be obtained at run time.
@Retention (retentionpolicy.runtime)//annotations exist in the class bytecode file, which can be obtained by reflection at run time
1.2, @Target: Define the purpose of the annotation
Java code
Copy Code code as follows:
@Target (Elementtype.type)//interfaces, classes, enumerations, annotations
@Target (Elementtype.field)//field, enumerated constants
@Target (Elementtype.method)//method
@Target (Elementtype.parameter)//Method parameters
@Target (Elementtype.constructor)//constructor
@Target (elementtype.local_variable)//local variable
@Target (Elementtype.annotation_type)//annotation
@Target (elementtype.package)///Package
ElementType can have multiple, one annotation can be class, method, field and so on
1.3. @Document: Note that this annotation will be included in Javadoc
1.4, @Inherited: Description Subclasses can inherit the annotation in the parent class
Here is an example of a custom annotation
2. Customization of annotations
Java code
Copy Code code as follows:
@Retention (Retentionpolicy.runtime)
@Target (Elementtype.method)
Public @interface HelloWorld {
Public String name () default "";
}
3, the use of annotations, test class
Java code
Copy Code code as follows:
public class SayHello {
@HelloWorld (name = "Xiaoming")
public void SayHello (String name) {
SYSTEM.OUT.PRINTLN (name + "Say hello world!");
}//www.heatpress123.net
}
4, Analytical notes
The Java reflection mechanism can help to get annotations with the following code:
Java code
Copy Code code as follows:
public class Anntest {
public void Parsemethod (class<?> clazz) {
Object obj;
try {
//Create a new object
obj = Clazz.getconstructor (new class[] {}) By default constructor. 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);
}
}