In-depth understanding of Java: Annotations (Annotation) Getting started with defining annotations
Learn about annotations in depth. We have to be able to define our own annotations and use annotations before we define our own annotations. We have to understand the syntax that Java provides us with the meta-annotations and related definition annotations.
Meta-Annotations:
The role of meta annotations is to annotate other annotations.
Java5.0 defines the 4 standard meta-annotation types. They 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 role of each meta-annotation and the instructions for how to use it for the corresponding number of references.
@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 narrative annotations (i.e., where the annotations described can be used)
The values (ElementType) are:
1.CONSTRUCTOR: Used for descriptive narrative constructors
2.FIELD: Used for descriptive narrative fields
3.local_variable: Used to describe local variables
4.METHOD: Used for descriptive narrative methods
5.PACKAGE: Used to describe the narrative package
6.PARAMETER: Used to describe the number of references
7.TYPE: For descriptive narrative classes, interfaces (including annotation types) or enum declarations
Usage examples:
@Target (Elementtype.type) public @Interface Table { /** * Datasheet name annotation, default value is class name @ return */public 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 the length of time that the annotation is retained: Some annotation are only present in the source code. and is discarded by the compiler. While others are compiled into class files, the annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when the class is loaded (note that it does not affect class execution, Because the 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 gaze information needs to be stored and used to describe the life cycle of the narrative annotation (i.e., the scope of the description of the narrative is valid)
The values (Retentionpoicy) are:
1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (i.e. class reserved)
3.RUNTIME: Valid at execution time (i.e. retained at execution time)
The Retention meta-annotation type has a unique value as a member. Its value is derived from the enumeration type value of Java.lang.annotation.RetentionPolicy.
The detailed real ratio is as follows:
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @Interface Column { publicdefault "FieldName"; Public default "SetField"; Public default "GetField"; Public Boolean default false ;}
The attribute value for the retentionpolicy of column annotations is rutime, so that the annotation processor can get the property values of the annotation through reflection. To do some logical processing at execution time.
@Documented:
@ Documented is used to describe the public API that other types of annotation should be labeled as program members. It is therefore possible to document such tools as Javadoc. Documented is a markup annotation with no members.
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documented public @Interface Column { publicdefault "FieldName"; Public default "SetField"; Public default "GetField"; Public Boolean default false ;}
@Inherited:
@Inherited meta-annotation is a markup annotation, @Inherited illustrates that a type that is labeled is inherited. Assuming that a annotation type using 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 such inheritance when the retention of the @inherited annotation type callout annotation is retentionpolicy.runtime.
Assuming that we use Java.lang.reflect to query a @inherited annotation type of annotation, 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 @Interface greeting {public enum fontcolor{bule,red,green}; String name (); default Fontcolor.green;}
Define your own annotations:
When you use @interface to define annotations yourself, you actively inherit the Java.lang.annotation.Annotation interface. The compiler itself completes the other details. When defining annotations, you cannot inherit other annotations or interfaces. @interface is used to declare an annotation, and each of these methods 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 a basic type, Class, String, enum). The default value of the parameter can be declared by using defaults.
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 modified with public or default access rights. For example, String value (); Here the method is set to Defaul default type;
Second, the 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 member is a string;
Thirdly, assuming that there is only one member, it is best to set the reference name to "value", followed by the parentheses. Example: The following example fruitname annotations have only one member of the parameters.
Simple self-defining annotations and using annotation instances:
Package annotation; Import java.lang.annotation.Documented; Import Java.lang.annotation.ElementType; Import java.lang.annotation.Retention; Import Java.lang.annotation.RetentionPolicy; Import Java.lang.annotation.Target; /** @author*/@Target (Elementtype.field) @Retention ( Retentionpolicy.runtime) @Documented public @Interface fruitname { default "";}
Packageannotation;Importjava.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@InterfaceFruitcolor {/*** Color Enumeration *@authorPeida **/ Public enumcolor{Bule,red,green}; /*** Color Properties *@return */Color Fruitcolor ()defaultColor.green;}
Packageannotation;Importannotation. Fruitcolor.color; Public classApple {@FruitName ("Apple") PrivateString Applename; @FruitColor (Fruitcolor=color.red)PrivateString AppleColor; Public voidSetapplecolor (String applecolor) { This. AppleColor =AppleColor; } PublicString Getapplecolor () {returnAppleColor; } Public voidsetapplename (String applename) { This. Applename =Applename; } PublicString Getapplename () {returnApplename; } Public voidDisplayName () {System.out.println ("The name of the fruit is: Apple"); }}
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. The value of a non-basic type annotation element cannot be null. Therefore, using an empty string or 0 as the default value is a frequently used practice. This constraint makes it very difficult for the processor to represent the presence or absence of an element. Because each annotation declaration, all elements exist, and all have corresponding values, in order to circumvent this constraint. We can only define a few special values. such as an empty string or a negative number. One time indicates that an element does not exist, which has become a customary use when defining annotations.
Like what:
1 Packageannotation;2 3 Importjava.lang.annotation.Documented;4 ImportJava.lang.annotation.ElementType;5 Importjava.lang.annotation.Retention;6 ImportJava.lang.annotation.RetentionPolicy;7 ImportJava.lang.annotation.Target;8 9 /**Ten * Notes for fruit suppliers One * @authorPeida A * - */ - @Target (Elementtype.field) the @Retention (retentionpolicy.runtime) - @Documented - Public@InterfaceFruitprovider { - /** + * Supplier Number - * @return + */ A Public intID ()default-1; at - /** - * Supplier Name - * @return - */ - PublicString name ()default""; in - /** to * Supplier Address + * @return - */ the PublicString address ()default""; *}
Defines the annotations. And when necessary to the relevant class, class attributes annotated information, assuming that there is no response to the annotated message processing process. Annotations can be said to be of no useful value.
How to make annotations really work. The main reason is the annotation processing method. Next we will learn the annotation information acquisition and processing!
In-depth understanding of Java: Annotations (Annotation) Getting started with defining annotations