Introduction to custom annotations based on Java annotations (Annotation) _java

Source: Internet
Author: User
Tags arrays inheritance reflection

To drill down into annotations, 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 of the meta annotations and the related definition annotations that Java provides for us.

--------------------------------------------------------------------------------

Meta Note:

The function of the meta annotation is to annotate other annotations. Java5.0 defines 4 standard meta-annotation types that are used to provide descriptions of other annotation types. Java5.0 defined meta Annotations:
1. @Target,
2. @Retention,
3. @Documented,
4. @Inherited
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 using the corresponding argument.

--------------------------------------------------------------------------------

@Target:

@Target describes the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, construction methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Using target in a annotation type of declaration can make it more explicit about the target that it modifies.

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

VALUES (ElementType) are:

1.CONSTRUCTOR: Used to describe the builder
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

Use instance:

Copy Code code as follows:

@Target (Elementtype.type)
Public @interface Table {
/**
* Datasheet name annotation, default value is class name
* @return
*/
Public String tablename () default "ClassName";
}

@Target (Elementtype.field)
Public @interface Nodbcolumn {

}


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

--------------------------------------------------------------------------------

@Retention:

@Retention defines how long the annotation is retained: Some annotation only appear in the source code and are discarded by the compiler, while others are compiled into 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 the class is not enforced because annotation is separated from the class in use). Use this meta-annotation to limit the lifecycle of annotation.

Role: 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 described annotation is valid)

VALUES (Retentionpoicy) are:

1.SOURCE: Valid in the source file (that is, source file retention)
2.CLASS: Valid in class file (that is, class reservation)
3.RUNTIME: Valid at run time (that is, run-time reservation)

The Retention meta-annotation type has a unique value as a member whose value comes from the Java.lang.annotation.RetentionPolicy enumeration type value. Specific examples are as follows:

Copy Code code as follows:

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

The Retentionpolicy property value of the column annotation is rutime so that the annotation processor can get the attribute value of the annotation through reflection, thus doing some run-time logical processing

--------------------------------------------------------------------------------

@Documented:

@Documented A common API that describes other types of annotation should be used as members of the annotated program, so it can be documented by tools such as Javadoc. Documented is a tagged annotation with no members.

Copy Code code as follows:

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

@Inherited:

A @Inherited meta annotation is a markup annotation @Inherited illustrates that a labeled type is inherited. If a annotation type using the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.

Note: The @Inherited annotation type is inherited by subclasses of the annotated class. The class does not inherit annotation 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 annotation @inherited annotation type callout is retentionpolicy.runtime. If we use Java.lang.reflect to query a @inherited annotation type of annotation, the reflection code check expands to work: Check class and its parent class until the specified annotation type is found. Or to the top level of the class inheritance structure.

Instance code:

Copy Code code as follows:

/**
*
* @author Peida
*
*/
@Inherited
Public @interface Greeting {
public enum fontcolor{Bule,red,green};
String name ();
FontColor fontcolor () default 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 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 the base type, Class, String, enum). You can declare the default value of a parameter via default.

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

The supported data types for the 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. All of the above types of arrays

How to set the parameters of the annotation type:
First, only two access rights, public or default, can be decorated. For example, String value (), where the method is set to the Defaul default type;
Second, the parameter members can only use the basic type Byte,short,char,int,long,float,double,boolean eight kinds of basic data types and string,enum,class,annotations data types, And some of these types of arrays. For example, String value (), where the parameter member is string;
Third, if there is only one parameter member, it is best to set the parameter name to "value" and then add the parentheses. Example: The following example Fruitname annotation has only one parameter member.

Simple custom annotations and use annotation instances:

Copy Code code as follows:

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;

/**
* Notes on the name of the fruit
* @author Peida
*
*/
@Target (Elementtype.field)
@Retention (Retentionpolicy.runtime)
@Documented
Public @interface Fruitname {
String value () default "";
}


Copy Code code as follows:

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;

/**
* Fruit Color annotation
* @author Peida
*
*/
@Target (Elementtype.field)
@Retention (Retentionpolicy.runtime)
@Documented
Public @interface Fruitcolor {
/**
* Color Enumeration
* @author Peida
*
*/
public enum color{Bule,red,green};

/**
* Color Properties
* @return
*/
Color fruitcolor () default color.green;

}


Copy Code code as follows:

package annotation;

import annotation. Fruitcolor.color;

public class Apple {

@FruitName ("Apple")
Private String Applename;

@FruitColor (fruitcolor=color.red)
Private String AppleColor;




public void Setapplecolor (String applecolor) {
This.applecolor = AppleColor;
}
Public String Getapplecolor () {
return applecolor;
}


public void Setapplename (String applename) {
This.applename = Applename;
}
Public String Getapplename () {
return applename;
}

public void DisplayName () {
System.out.println ("Fruit's name is: Apple");
}
}


The annotation is defined and the annotation information is added to the relevant class, class attribute when needed, and the annotation can be said to have no practical value if there is no response to the annotation processing process. How to make annotations really play a role, mainly in the annotation processing method, next we will implement a simple ORM through annotations, to further study the annotations, to use annotations!

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.