Annotations (Annotation) are features that are added starting from jdk1.5. Learning annotations can read framework code, make programming more concise, and code clearer.
Annotation concept: Java provides a way and method for associating any information and any metadata with elements in the original program.
annotations require import java.lang.annotation.*;
Java comes with 3 annotations:
- @Override//Coverage
- @Deprecated//Obsolete
- @SuppressWarnings ()//Suppress warning
Syntax requirements for custom annotations
The code for general custom annotations is as follows://"Description annotation" in the following pest will use O (∩_∩) o
The @Target ({elementtype.method,elementtype.type})//scope is on a method, class, or interface.
@Retention (Retentionpolicy.runtime)
@Inherited//Allow subclass inheritance (you annotate a parent class, the subclass inherits the annotations of the parent class)
@Documented//Generate doc with annotated information
Public @interface Description {//Use @interface keyword to define annotations
String desc ();//member declared without argument or exception
String author ();
int age () default 18;//you can set a defaults for a member
}
Explain:
Meta-annotations, which are annotations, @Target, @Retention, @Inherited, @Documented are meta annotations.
The @Target values are:
- Elementtype.type//interfaces, classes, enumerations, annotations
- Elementtype.field/constants for fields, enumerations
- elementtype.method//method
- elementtype.parameter//Method Parameters
- elementtype.constructor//constructor function
- elementtype.local_variable//Local Variables
- elementtype.annotation_type//annotations
- elementtype.package///Bag
Retention: Reserved, defines the retention policy for annotations. There are 3 values: SOURCE, CLASS, RUNTIME.
- Source is displayed only in the source code and is discarded at compile time.
- The class is recorded in class at compile time and is ignored at runtime.
- Runtime is present and can be read by reflection. The execution of the main method is run-time.
The member type is restricted, and the legal type includes the original type and String,class,annotation, enumeration.
When the annotation has only one member, the member name must be named value (), because it is customary for us to write parameter names and assignment numbers. Directly to the parameter value. Simple and convenient. Allows you to peek at the following annotation class mydescription.
Note Classes can have no members, and annotations with no members are called identity annotations. such as Springmvc inside the @controller, is the logo annotation.
Parsing annotations: Obtain runtime annotation information on a class, function, or member by reflection to achieve the logic of dynamic control program operation.
1 PackageCom.rainmer.anno;2 3 Importjava.lang.annotation.*;4 5 /**6 * Created by Simon Sun on 2015/7/22.7 */8 @Target ({elementtype.method,elementtype.type})9 @Retention (retentionpolicy.runtime)Ten @Inherited One @Documented A Public@Interfacemydescription { - PublicString value (); -}
1 PackageCom.rainmer.anno;2 3 /**4 * Created by Simon Sun on 2015/7/22.5 */6@MyDescription ("I Am Interface")7 Public InterfacePerson {8@MyDescription ("I Am Interface method")9 PublicString name ();Ten Public intAge (); One Public voidsing (); A}
1 PackageCom.rainmer.anno;2 3 /**4 * Created by Simon Sun on 2015/7/22.5 */6@MyDescription ("I am a class annotation")7 Public classChildImplementsPerson {8 @Override9@MyDescription ("I am a method annotation")Ten@Description (desc = "The name method", author = "Mook Boy") One PublicString name () { A return NULL; - } - the @Override - Public intAge () { - return0; - } + - @Override + Public voidSing () { A at } -}
1 PackageCom.rainmer.anno;2 3 Importjava.lang.annotation.Annotation;4 ImportJava.lang.reflect.Method;5 6 /**7 * Created by Simon Sun on 2015/7/22.8 */9 Public classParseanno {Ten Public Static voidMain (string[] args) { One //1. Load class with class loader A Try { -Class C = class.forname ("Com.rainmer.anno.Child"); - //to determine if Kevresan has mydescription such annotations the BooleanIsexist = C.isannotationpresent (mydescription.class); - if(isexist) { - //3. Get the Annotated instance -Mydescription mydescription = (mydescription) c.getannotation (mydescription.class); + System.out.println (Mydescription.value ()); - } + A //4. Find the annotations on the method atMethod[] ms =c.getmethods (); - for(Method m:ms) { - BooleanIsmexist = M.isannotationpresent (mydescription.class); - if(ismexist) { -Mydescription d = m.getannotation (mydescription.class); - System.out.println (D.value ()); in } - } to + //Another kind of analytic method - for(Method m:ms) { theAnnotation[] as =m.getannotations (); * for(Annotation a:as) { $ if(Ainstanceofmydescription) {Panax NotoginsengMydescription d =(Mydescription) A; - System.out.println (D.value ()); the } + } A } the}Catch(ClassNotFoundException e) { + e.printstacktrace (); - } $ $ } -}
Program output:
I am a class annotation
I am a method annotation
I am a method annotation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inheritance not only inherits the annotations of the class, but also inherits the annotations of the method, provided that the subclass does not overwrite the parent class's methods.
Here's a chestnut:
1 PackageCom.rainmer.anno;2 3 /**4 * Created by Simon Sun on 2015/7/22.5 */6@MyDescription ("I Am parent class")7 Public classAnimal {8@MyDescription ("I am Parent method")9 PublicString GetName () {Ten return NULL; One }; A}
1 Package Com.rainmer.anno; 2 3 /** 4 * Created by Simon Sun on 2015/7/22. 5 */ 6 Public class extends Animal {78 }
The parsing class Parseanno as long as the 13th behavior is modified: Class C = Class.forName ("Com.rainmer.anno.Dog");
Program output:
I am parent class
I am Parent method
I am Parent method
But if the dog covers the GetName method, then the output becomes:
I am parent class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Finally, add some spice, Idea's two useful shortcut keys:
ALT + ENTER:Add exception or fast try/catch; Force type conversion.
Alt+insert: Generate code, such as Get, set method, constructor, and, of course, can also be used to quickly overwrite the interface or the method of the parent class
SOURCE Download: http://yunpan.cn/ccWaszMAARdJb access password d806
Getting Started with Java annotations (including source download)