Java Annotation trial and Java Annotation trial

Source: Internet
Author: User

Java Annotation trial and Java Annotation trial

Many features of Java are similar, such as multithreading, io, and collection classes. However, they are not summarized. Today Annotation is used, so let's just summarize it.

 

To use Annotation, you must first understand the Metadata Annotation.

Meta AnnotationThe role 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

 

@ Target:

@ Target Annotation specifies the type range modified by Annotation, such as Method and Filed. Annotation can be used for packages, types (class, interface, enumeration, Annotation type), type members (method, constructor, member variables, and enumeration values), method parameters and local variables (such as loop variables and catch parameters)

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

@ Retention:

 @ RetentionDefines the duration of Annotation retention: 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)

 

@ Brief ented:

  @Documented is used to describe other types of annotation which should be used as a 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.

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

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.

The above is the introduction and definition of annotations, but only the annotation processor can play a role.

Annotation processor:

Annotation processor class library (java. lang. reflect. AnnotatedElement ):

Java uses the Annotation interface to represent the Annotation before the program element. This interface is the parent interface of all Annotation types. In addition, Java added the AnnotatedElement interface under the java. lang. reflect package. This interface represents the program elements that can be annotated in the program. This interface mainly has the following implementation classes:

Class: Class Definition
Constructor: Constructor Definition
Field: Tired member variable definition
Method: class Method definition
Package: Class Package Definition

The java. lang. reflect package mainly contains some tool classes for implementing the reflection function. In fact, all the reflection APIs provided by the java. lang. reflect package expand the ability to read Annotation information during runtime. After an Annotation type is defined as a runtime Annotation, the Annotation can be visible at runtime. When the class file is loaded, the Annotation stored in the class file will be read by the virtual machine.
The AnnotatedElement interface is the parent interface of all program elements (Class, Method, and Constructor). Therefore, after the program obtains the AnnotatedElement object of a Class through reflection, the program can call the following four methods of the object to access the Annotation information:

Method 1: <T extends Annotation> T getAnnotation (Class <T> annotationClass): returns the Annotation of the specified type on the modified program element. If the Annotation of this type does not exist, returns null.
Method 2: Annotation [] getAnnotations (): returns all annotations on the program element.
Method 3: boolean is AnnotationPresent (Class <? Extends Annotation> annotationClass): determines whether the program element contains the specified type of Annotation. If the Annotation exists, true is returned; otherwise, false is returned.
Method 4: Annotation [] getDeclaredAnnotations (): returns all comments directly on this element. Unlike other methods in this interface, this method ignores the inherited comments. (If no annotation exists directly on this element, an array with zero length is returned .) The caller of this method can modify the returned array at will; this will not affect the array returned by other callers.

Below is a simpleSample Code:

Package test; import java. lang. reflect. method;/*** @ author Ywind E-mail: guoshukang@vip.qq.com * @ version Creation Time: May 26, 2015 9:09:59 * annotation processor **/public class AnnotationT {static {Class <?> Cls = null; try {cls = Class. forName ("test. annotationTest ");} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} Method [] methods = cls. getMethods (); for (Method method: methods) {if (method. isAnnotationPresent (Test. class) {Test test = method. getAnnotation (Test. class); System. out. print (test. value () ;}}} public static void main (String [] args ){}}
Package test; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/*** @ author Ywind E-mail: guoshukang@vip.qq.com * @ version Creation Time: May 26, 2015 9:00:00 * annotation example **/@ Retention (RetentionPolicy. RUNTIME) @ Target (ElementType. METHOD) public @ interface Test {String value ();}
Package test;/*** @ author Ywind E-mail: guoshukang@vip.qq.com * @ version Creation Time: may 26, 2015 9:02:43 * annotation example **/public class AnnotationTest {@ Test ("String") public void Good (){}}

Basic summary from http://www.cnblogs.com/peida/tag/Annotation/ thanks @ peida

 

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.