[3] Annotations (Annotation)--in-depth understanding of Java: Annotations (Annotation)--annotations processor

Source: Internet
Author: User

Reprint http://www.cnblogs.com/peida/archive/2013/04/26/3038503.html

In-depth understanding of Java: Annotations (Annotation)--annotations processor

If there is no method or work to read the annotations, then annotations are no more useful than annotations. An important part of the process of using annotations is to create them using the annotation processor. Java SE5 extends the reflection mechanism API to help programmers quickly construct custom annotation processors.

Note Processor Class library (java.lang.reflect.AnnotatedElement):

Java uses the annotation interface to represent annotations in front of the program element, which is the parent interface for all annotation types. In addition, Java has added a annotatedelement interface under the Java.lang.reflect package, which represents a program element that can accept annotations in the program, which has the following implementation classes:

Class: Classes Definition
Constructor: Constructor definition
Field: Tired member variable definition
Method: Methods Definition of Class
Package: Packages definition for Class

The Java.lang.reflect package consists of a number of tool classes that implement the reflection function, and in fact, the Java.lang.reflect package provides the ability to read runtime annotation information with all the provided reflection APIs. When a annotation type is defined as a run-time annotation, the annotation is visible to the runtime, and the annotation stored in the class file is read by the virtual machine when the class file is loaded.
The Annotatedelement interface is the parent interface for all program elements (class, method, and constructor), so the program obtains the Annotatedelement object for a class by 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 an annotation of the specified type that exists on the modified program element, if the type annotation does not exist, Then NULL is returned.
Method 2:annotation[] Getannotations (): Returns all annotations that exist on the program element.
Method 3:boolean is annotationpresent (class<?extends annotation> annotationclass): Determines whether the program element contains annotations of the specified type, and returns True if present. Otherwise, false is returned.
Method 4:annotation[] Getdeclaredannotations (): Returns all annotations that exist directly on this element. Unlike other methods in this interface, the method ignores inherited annotations. (if no comment exists directly on this element, an array of zero length is returned.) The caller of the method can arbitrarily modify the returned array, which does not have any effect on the array returned by other callers.

A simple annotation Processor:

/**Note Declaration ***************//*** Fruit Name Notes *@authorPeida **/@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @DocumentedPublic @InterfaceFruitname {String value ()Default "";}/*** Fruit Color Annotations *@authorPeida **/@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @DocumentedPublic @InterfaceFruitcolor {/*** Color Enumeration *@authorPeida **/PublicEnumcolor{Bule,red,green};/*** Color Properties *@return*/Color Fruitcolor ()DefaultColor.green;}/*** Notes for fruit suppliers *@authorPeida **/@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @DocumentedPublic @InterfaceFruitprovider {/*** Supplier Number *@return*/Publicint ID ()Default-1;/*** Supplier Name *@return*/Public String name ()Default "";/*** Supplier Address *@return*/Public String address ()Default "";}/**Annotations using ***************/PublicClassApple {@FruitName ("Apple")PrivateString Applename; @FruitColor (fruitcolor=color.red)PrivateString AppleColor; @FruitProvider (id=1,name= "Shaanxi Red Fuji Group", address= "No. 89th, Yan an LU, Xi ' an city, Shaanxi province")PrivateString Appleprovider;PublicvoidSetapplecolor (String applecolor) {This.applecolor =AppleColor; }PublicString Getapplecolor () {ReturnAppleColor; }PublicvoidSetapplename (String applename) {This.applename =Applename; }PublicString Getapplename () {ReturnApplename; }PublicvoidSetappleprovider (String appleprovider) {This.appleprovider =Appleprovider; }PublicString Getappleprovider () {ReturnAppleprovider; }PublicvoidDisplayName () {System.out.println ("The name of the fruit is: Apple"); }}/**Note Processor ***************/PublicClassFruitinfoutil {PublicStaticvoid Getfruitinfo (class<?>Clazz) {String strfruitname= "fruit Name:"; String strfruitcolor= "Fruit color:"; String strfruitprovicer= "Supplier Information:"; field[] Fields =Clazz.getdeclaredfields ();For(Field field:fields) {if (Field.isannotationpresent (fruitname.Class{Fruitname Fruitname = (fruitname) field.getannotation (fruitname.Class); strfruitname=strfruitname+Fruitname.value (); System.out.println (Strfruitname); }Elseif (Field.isannotationpresent (Fruitcolor.Class) {Fruitcolor fruitcolor= (fruitcolor) field.getannotation (Fruitcolor.Class); strfruitcolor=strfruitcolor+Fruitcolor.fruitcolor (). toString (); System.out.println (Strfruitcolor); }Elseif (Field.isannotationpresent (Fruitprovider.Class) {Fruitprovider fruitprovider= (fruitprovider) field.getannotation (Fruitprovider.Class); strfruitprovicer= "Supplier Number:" +fruitprovider.id () + "supplier Name:" +fruitprovider.name () + "supplier Address:" +Fruitprovider.address (); System.out.println (Strfruitprovicer); } } }}/*********** Output ************** */Public class Fruitrun { /** * @param args *  /public static void main (string[] args) {fruitinfoutil.getfruitinfo (Apple.  Class); }}==================================== fruit Name: Apple fruit Color: Red supplier Number: 1 supplier Name: Shaanxi Red Fuji Group supplier Address: Yan an LU, Xi ' an city, Shaanxi Province, No. 89th, Red Fuji building 

The basics of Java annotations (see the map below) are basically all over again, the next we can synthesize the application and further deepen the understanding and application of the various knowledge points of annotations by designing a simple ORM framework based on annotations.

[3] Annotations (Annotation)--in-depth understanding of Java: Annotations (Annotation)--annotations processor

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.