[2] Annotations (Annotation)--in-depth understanding of Java: Annotations (Annotation) Getting Started with custom annotations

Source: Internet
Author: User

Reprint http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html

In-depth understanding of Java: Annotations (Annotation) Getting Started with custom annotations

  To learn more about annotations, we must be able to define our own annotations and use annotations to define our own annotations before we have to understand the syntax of the meta-annotations and related definition annotations that Java provides us.

Meta-Annotations:

The role of meta annotations is to be responsible for annotating other annotations. Java5.0 defines 4 standard meta-annotation types, which are used to provide descriptions of other annotation types. Java5.0 defined meta-annotations:
[Email protected],
[Email protected],
[Email protected],
[Email protected]
These types and the classes they support can be found in the Java.lang.annotation package. Let's take a look at the function of each meta-annotation and the instructions for using the corresponding sub-parameters.

  @Target:

@Target illustrates the range of objects that annotation modifies: annotation can be used for 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). Target can be more clearly decorated by using target in the declaration of the annotation type.

  Function: Used to describe the scope of use of annotations (i.e., where the annotations described can be used)

 The values (ElementType) are:

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

Usage examples:

@Target (elementtype.type) public@interface Table {    /**Default "ClassName";} @Target (Elementtype.field) public@interface nodbcolumn {}       

Note Table can be used for annotation classes, interfaces (including annotation types), or enum declarations, and annotation nodbcolumn can only be used for member variables of the annotation class.

@Retention:

 @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)

 The values (Retentionpoicy) are:

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)

The Retention meta-annotation type has a unique value as a member, and its value is derived from the enumeration type value of Java.lang.annotation.RetentionPolicy. The concrete examples are as follows:

  @Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @interface Column { public String name () ; public String setfuncname () default "SetField" ; public String getfuncname () default "GetField" ; public boolean defaultdbvalue () default false      

The attribute value of the retentionpolicy of column annotations is rutime so that the annotation processor can get the property value of the annotation by reflection, thus doing some logic processing of the runtime

@Documented:

  @ Documented is 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.

  @Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documented Span style= "color: #0000ff;"    >public @interface Column { public String name () ; public String setfuncname () default "SetField" ; public String getfuncname () default "GetField" ; public boolean defaultdbvalue () default false      

@Inherited:

  @Inherited meta-annotation 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.

Note: @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 annotation from the method it overloads.

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.

Instance code:

/** * @author * *  @Inherited public@interfaceenumdefault fontcolor.green;} 

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.

  To define the annotation format:
Public @interface annotation name {definition body}

  Supported data types for annotation parameters:

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.

Simple custom annotations and examples of using annotations:

PackageAnnotationImportjava.lang.annotation.Documented;Import Java.lang.annotation.ElementType; import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy; Import Java.lang.annotation.target; /** * fruit Name annotated *  @author */ @Target (Elementtype.field) @Retention ( Retentionpolicy.runtime) @Documented public @ Fruitname {String value () default" ;} 
PackageAnnotationImportjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;ImportJava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/*** Fruit Color Annotations *@authorPeida **/ @Target (Elementtype.field) @Retention ( Retentionpolicy.runtime) @Documented public @ Fruitcolor {/**  * Color Enumeration *  @author  Peida * Span style= "color: #008000;" >*/public enum color{ Bule,red,green}; /** @return Span style= "color: #008000;" >*/ color Fruitcolor () default  Color.green;}            
PackageAnnotationImportAnnotation. Fruitcolor.color;PublicClassApple {@FruitName ("Apple")PrivateString Applename; @FruitColor (fruitcolor=color.red)PrivateString AppleColor;PublicvoidSetapplecolor (String applecolor) {this.applecolor = AppleColor;} public String Getapplecolor () {return AppleColor; } public voidthis.applename = Applename; } public String Getapplename () {return Applename;} public void     

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. For example

1PackageAnnotation23Importjava.lang.annotation.Documented;4ImportJava.lang.annotation.ElementType;5ImportJava.lang.annotation.Retention;6ImportJava.lang.annotation.RetentionPolicy;7ImportJava.lang.annotation.Target;89/**10* Notes for fruit Suppliers11*@authorPeida12*13*/14@Target (Elementtype.field)15@Retention (Retentionpolicy.runtime)16@Documented17Public @InterfaceFruitprovider {18/**19* Supplier number20*@return21st*/22Publicint ID ()Default-1;2324/**25* Supplier Name26 *  @return 27 */28 public String name () default "" ; 30 /**31 32  *  @return Span style= "color: #008080;" >33 */34 public String Address () default "" ;                 

Annotations are defined and, when needed, annotated information is given to related classes, class attributes, and annotations can be said to be of no practical value if there is no response to the annotated message processing flow. How to make annotations really play a role, mainly in the annotation processing method, next we will learn the annotation information acquisition and processing!

[2] Annotations (Annotation)--in-depth understanding of Java: Annotations (Annotation) Getting Started with custom annotations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.