Original link: http://blog.csdn.net/u013045971/article/details/53433874
What are annotations
Annotation (note) Is that Java provides a way and a way for an element in a meta-program to correlate any information with any metadata (metadata). Annotion (annotation) is an interface that a program can use to get the Annotion object of a specified program element, and then obtain the metadata within the annotation by Annotion object.
Annotation (note) was introduced in JDK5.0 and later versions. It can be used to create documents, track dependencies in code, and even perform basic compile-time checks. In some ways, annotation is used like a modifier and is applied to the declaration of a package, a type, a constructor method, a method, a member variable, a parameter, a local variable. This information is stored in the annotation "name=value" structure pair.
What is metadata meta data
Metadata is translated from the word metadata, which means "data about data".
There are many functions of meta data, such as: You may have used Javadoc annotations to automatically generate documents. This is one of the meta-data functions. In general, metadata can be used to create documents, keep track of code dependencies, and perform compile-time format checks instead of existing configuration files. If you want to classify the role of metadata, there is no clear definition, but we can according to its role, broadly can be divided into three categories:
1. Writing a document: Generating a document from the metadata identified in the code
2. Code Analysis: Analyze code with metadata identified in code
3. Compile check: The compiler can implement the basic compilation check through the metadata identified in the code
Annotation and annotation types
Annotation uses the new syntax introduced in java5.0, which behaves much like a modifier such as public and final. Each annotation has a name and a number of members >=0. Each member of the annotation has a name and value (like JavaBean) called the Name=value pair, and name=value loads the annotation information.
The annotation type defines the annotation name, type, and member default values. A annotation type can be said to be a special Java interface whose member variables are restricted, and the new syntax is required when declaring annotation types. When we access annotation through the Java Reflection API, the return value will be an object that implements the annotation type interface, which we can easily access to its annotation members by accessing this object. The following chapters will refer to the 3 standard annotation types contained in the Java.lang package of java5.0.
Classification of annotations
According to the number of parameters of the note classification:
1. Tag annotations, a annotation type without a member is called a tag annotation, and this type simply uses its own presence or not to provide information to us, such as common @override
2. Single value annotations
3. Full annotations
Classification according to the method and use of the annotations:
1.JDK built-in system annotations
2. Meta-annotations
3. Custom annotations
Meta annotations
The role of meta annotations is to annotate other annotations, and Java 5.0 defines 4 meta-annotation types to provide a description of the type of annotation that love him.
java.lang.annotation
[email protected]
[email protected]
[email protected]
[email protected]
@Target
Decorated Object scopes: packages, types (classes, interfaces, enumerations, annotation types), type members (methods, constructor methods, member variables, enumeration values), method parameters, and local variables such as loop variables, catch parameters.
function: Used to describe the scope of use of annotations.
ElementType Value:
1.CONSTRUCTOR: Used to describe the constructor
2.FIELD: Used to describe the domain
3.local_variable: Used to describe local variables
4.METHOD: Used to describe the method
5.PACKAGE: Used to describe the package
6.PARAMETER: Used to describe parameters
7.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations
For example:
Name can annotate member variables of a class
@Target (Elementtype.field) @Documentedpublic @interface Name { String value () Default "";}
Person can annotate classes, interfaces (including annotation types), or enum declarations
@Target (elementtype.type) public @interface the person { String value () Default "";}
@Retention
defines how long the annotation is retained: Some annotation appear only in the source code and are discarded by the compiler, while others are compiled in the class file The annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that it does not affect class execution because annotation is separated from the class in use). Using this meta-annotation can limit the "life cycle" of annotation.
function: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope of the annotation being described is valid)
Retentionpoicy Value
1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (that is, class reserved)
3.RUNTIME: Valid at run time (that is, runtime retention)
For example:
The value of the retentionpolicy of the name annotation is runtime, so that the annotation processor can obtain the properties of the annotation through reflection, thus doing some logical processing of the runtime.
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Name { String value ( Default "";}
@Document
Used to describe other types of annotation that should be used as public APIs for annotated program members, so they can be documented by tools such as Javadoc. Documented is a markup annotation with no members.
function: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope in which the described annotation is valid).
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Name { String value ( Default "";}
@Inhrited
is a markup annotation, @Inherited illustrates that a type that is labeled is inherited. If a annotation type that uses the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.
@Inherited The annotation type is inherited by subclasses of the class being labeled. The annotation class does not inherit from the interface it implements, and the method does not inherit from the method it overloads annotation
The Reflection API enhances this inheritance when the retention of the @inherited annotation type callout annotation is retentionpolicy.runtime. If we use Java.lang.reflect to query the annotation of a @inherited annotation type, the reflection code check will work: Examine the class and its parent class until the specified annotation type is found, or reach the top level of the class inheritance structure.
Custom annotations
When you use @interface to customize annotations, the Java.lang.annotation.Annotation interface is automatically inherited and other details are automatically completed by the compiler. When you define annotations, you cannot inherit other annotations or interfaces. @interface is used to declare an annotation, in which each method actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter (the return value type can only be base type, Class, String, enum). You can declare the default value of a parameter through default.
Custom annotation formats:
Public @interface Note name {callout Body}
1. All basic data Types (Int,float,boolean,byte,double,char,long,short)
2.String type
3.Class type
4.enum type
5.Annotation type
6. Arrays of all types above
How to set the parameters of the annotation type:
First, it can only be decorated with public or default access rights. For example, String value (); Here the method is set to Defaul default type;
Second, parameter members can only use basic types Byte,short,char,int,long,float,double,boolean eight basic data types and string,enum,class,annotations data types, As well as these types of arrays. For example, String value (), where the parameter member is string;
Thirdly, if there is only one parameter member, it is best to set the parameter name to "value", followed by parentheses. Example: The following example Fruitname annotation has only one parameter member.
For example:
Name Name annotation:
/** * Created by Mingwei on 12/2/16. * <p/> * Name annotation */@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Name { String value () Default "";}
Gander Gender Annotations:
/** * Created by Mingwei on 12/2/16. * Gender Annotations */@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Gender { public enum Gendertype { Male ("male"), Female ("female"), other ("neutral"); Private String genderstr; Private Gendertype (String arg0) { this.genderstr = arg0; } @Override public String toString () { return genderstr; } } Gendertype gender () default Gendertype.male;}
Profile Profiles Note:
/** * Created by Mingwei on 12/2/16. * Basic Data Note */@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface profile { /** * ID * * @return * * /public int id () default-1; /** * Height * @return * /public int height () default 0; /** * Native Place * @return */public String nativeplace () Default "";}
default values for annotation elements
The annotation element must have a definite value, either specified in the default value of the definition annotation, or specified when the annotation is used, and the value of a non-basic type of annotation element cannot be null. Therefore, using an empty string or 0 as the default value is a common practice. This constraint makes it difficult for the processor to represent the presence or absence of an element, because in each annotation declaration, all elements are present and have corresponding values, in order to circumvent this constraint, we can only define special values, such as an empty string or a negative number, once to indicate that an element does not exist, and when defining annotations, This has become a customary usage.
Note Processor Class library (java.lang.reflect.AnnotatedElement)
Annotation element Java uses the annotation interface to represent the annotations preceding the program element, which is the parent interface for all annotation types. In addition, Java has added a annotatedelement interface under the Java.lang.reflect package, which represents a program element that can accept annotations in the program, which has the following implementation classes:
class: Classes definition
Constructor: constructor definition
Field: tired member variable definition
Method: Methods Definition of Class
Package: Packages definition for Class
When a annotation is defined as run-time annotation, the annotation is visible at run time, and the annotation that is stored in the class file when the class file is loaded will be read by the virtual elder sister. Annotatedelement
The interface provides the following four methods to access annotation information:
Method 1:<t extends annotation> T getannotation (class<t> annotationclass): Returns annotations of the specified type that exist on the program element, if the If the type annotation does not exist, NULL is returned.
Method 2:annotation[] Getannotations (): Returns all annotations that exist on the program element.
Method 3:boolean is annotationpresent (class<?extends annotation> annotationclass): Determines whether the program element contains annotations of the specified type, existence Returns TRUE, otherwise false is returned.
Method 4:annotation[] Getdeclaredannotations (): Returns all annotations that exist directly on this element. Unlike other methods in this interface, the method ignores inherited annotations. (if no comment exists directly on this element, an array of zero length is returned.) The caller of the method can arbitrarily modify the returned array, which does not have any effect on the array returned by other callers.
We write a simple processor for the custom annotations defined previously:
/** * Created by Mingwei on 12/2/16. */public class Customutils {public static void GetInfo (Class<?> clazz) {String name = ""; String gender = ""; String profile = ""; Field fields[] = Clazz.getdeclaredfields (); for (Field field:fields) {if (Field.isannotationpresent (Name.class)) {Name arg0 = Field.geta Nnotation (Name.class); Name = name + Arg0.value (); LOG.I ("GMW", "name=" + name); } if (Field.isannotationpresent (Gender.class)) {Gender arg0 = field.getannotation (Gender.class) ; Gender = gender + Arg0.gender (). toString (); LOG.I ("GMW", "gender=" + gender); } if (Field.isannotationpresent (Profile.class)) {Profile arg0 = field.getannotation (profile.cla SS); Profile = "[id=" + arg0.id () + ", height=" + arg0.height () + ", nativeplace=" + arg0.nativeplace () + "]"; LOG.I ("GMW", "profile=" + profile); } } }}
To use a custom annotation:
/** * Created by Mingwei on 12/2/16. */public class Person { @Name ("Atrobos") private String Name; @Gender (Gender = Gender.GenderType.Male) private String Gender; @Profile (id = 1001, height = n, nativeplace = "CN") private String profile; Public String GetName () { return name; } public void SetName (String name) { this.name = name; } Public String Getgender () { return gender; } public void Setgender (String gender) { this.gender = gender; } Public String GetProfile () { return profile; } public void Setprofile (String profiles) { this.profile = profile; }}
Run:
Customutils.getinfo (Person.class);
Output:
i/gmw:gender= male i/gmw:name= Atrobos I/GMW:PROFILE=[ID=1001,HEIGHT=180,NATIVEPLACE=CN]
original link: http://blog.csdn.net/u013045971/article/details/53433874
One hour to figure it out. Custom Annotations (Annotation)