Introduction to custom annotations Based on Java annotations

Source: Internet
Author: User

To learn about annotations in depth, we must be able to define our own annotations and use annotations. Before defining our own annotations, we must understand the syntax of the Meta annotation and related definition annotation provided by Java for us.

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

Meta annotation:

The role of meta-annotation is to annotate other annotations. Java5.0 defines four standard meta-annotation types, which are used to provide instructions on other annotation types. Meta annotation defined by Java5.0:
1. @ Target,
2. @ Retention,
3. @ brief ented,
4. @ Inherited
These types and their supported classes can be found in the java. lang. annotation package. Next, let's take a look at the functions of each element annotation and the instructions for using corresponding sub-parameters.

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

@ Target:

@ Target indicates the range of objects modified by Annotation: Annotation can be used for packages, types (class, interface, enumeration, Annotation type) type members (methods, constructor methods, member variables, enumerated values), method parameters, and local variables (such as cyclic variables and catch parameters ). In the Annotation type declaration, target can be used to better clarify the object to be modified.

Purpose: Describe the scope of use of the annotation (that is, where the description can be used)

Values:

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

Instance used:

Copy codeThe Code is as follows: @ Target (ElementType. TYPE)
Public @ interface Table {
/**
* Data Table Name annotation. The default value is the class name.
* @ Return
*/
Public String tableName () default "className ";
}

@ Target (ElementType. FIELD)
Public @ interface NoDBColumn {

}

Annotation Table can be used for annotation class, interface (including annotation type) or enum declaration, and annotation NoDBColumn can only be used for annotation class member variables.

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

@ Retention:

@ Retention defines the Retention duration of the Annotation: Some Annotation only appears in the source code and is discarded by the compiler; others are compiled in the class file; annotation compiled in the class file may be ignored by the virtual machine, while others will be read when the class is loaded (Please note that the execution of the class is not affected, because Annotation and class are separated in use ). This meta-Annotation can be used to limit the "Life Cycle" of Annotation.

Purpose: indicates the level at which the annotation information needs to be saved and used to describe the lifecycle of the annotation (that is, within the scope of the description)

Values (RetentionPoicy) include:

1. SOURCE: valid in the SOURCE file (that is, the SOURCE file is retained)
2. CLASS: valid in the class file (that is, the class is retained)
3. RUNTIME: valid during RUNTIME (that is, reserved during RUNTIME)

The Retention meta-annotation type has a unique value as a member. Its value comes from the enumeration type value of java. lang. annotation. RetentionPolicy. The specific example is as follows:

Copy codeThe Code is 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 attribute value of the RetentionPolicy of the Column annotation is RUTIME, so that the annotation processor can obtain the attribute value of the annotation through reflection, so as to perform some runtime logic processing.

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

@ Brief ented:

@ Brief ented is used to describe other types of annotation which should be used as the public API of the labeled Program Member. Therefore, it can be Documented by tools such as javadoc. Incluented is a tag Annotation with no members.

Copy codeThe Code is as follows: @ Target (ElementType. FIELD)
@ Retention (RetentionPolicy. RUNTIME)
@ Brief ented
Public @ interface Column {
Public String name () default "fieldName ";
Public String setFuncName () default "setField ";
Public String getFuncName () default "getField ";
Public boolean defaultDBValue () default false;
}

@ Inherited:

@ Inherited meta annotation is a tag annotation. @ Inherited describes that a labeled type is Inherited. If an annotation type modified with @ Inherited is used for a class, this annotation will be used for the subclass of this class.

Note: The @ Inherited annotation type is Inherited by the subclass of the labeled class. The class does not inherit annotation from the interface it implements, and the method does not inherit annotation from the method it loads.

When the Retention of annotation marked by @ Inherited annotation is RetentionPolicy. RUNTIME, the reflection API enhances this inheritance. If we use java. lang. when reflect queries an annotation of the @ Inherited annotation type, the reflection code check starts: Check the class and its parent class until the specified annotation type is found, or you can reach the top layer of the class inheritance structure.

Instance code:

Copy codeThe Code is as follows :/**
*
* @ Author peida
*
*/
@ Inherited
Public @ interface Greeting {
Public enum FontColor {BULE, RED, GREEN };
String name ();
FontColor fontColor () default FontColor. GREEN;
}

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

Custom annotation:

When the @ interface custom annotation is used, the java. lang. Annotation. annotation interface is automatically inherited, and other details are automatically completed by the compiler. You cannot inherit other annotations or interfaces when defining annotations. @ Interface is used to declare an annotation. Each method actually declares a configuration parameter. The method name is the parameter name, and the return value type is the parameter type (the return value type can only be basic type, Class, String, or enum ). You can use default to declare the default value of a parameter.

Define annotation format:
Public @ interface annotation name {definition body}

Data Types supported by 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 types of arrays above

How to set parameters in the Annotation type:
First, only public or default access permissions can be modified. For example, String value (); here the method is set to defaul default type;
Second, parameter members can only use eight basic data types: byte, short, char, int, long, float, double, and boolean, and data types such as String, Enum, Class, and annotations, and these types of arrays. for example, String value (); here the parameter member is String;
Third, if there is only one parameter member, it is best to set the parameter name to "value", followed by parentheses. For example: The FruitName annotation in the following example has only one parameter member.

Simple user-defined annotation and usage annotation example:

Copy codeThe Code is as follows: package annotation;

Import java. lang. annotation. incluented;
Import java. lang. annotation. ElementType;
Import java. lang. annotation. Retention;
Import java. lang. annotation. RetentionPolicy;
Import java. lang. annotation. Target;

/**
* Fruit name Annotation
* @ Author peida
*
*/
@ Target (ElementType. FIELD)
@ Retention (RetentionPolicy. RUNTIME)
@ Brief ented
Public @ interface FruitName {
String value () default "";
}

Copy codeThe Code is as follows: package annotation;

Import java. lang. annotation. incluented;
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)
@ Brief ented
Public @ interface FruitColor {
/**
* Color Enumeration
* @ Author peida
*
*/
Public enum Color {BULE, RED, GREEN };

/**
* Color attributes
* @ Return
*/
Color fruitColor () default Color. GREEN;

}

Copy codeThe Code is 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 name: Apple ");
}
}

Annotations are defined, and annotation information is added to related classes and class attributes as needed. If there is no response to the annotation information processing process, annotations can be said to be of no practical value. How to make annotations really play a role mainly lies in the annotation processing method. In the next step, we will implement a simple ORM through annotations to thoroughly learn annotations and 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.