Java Annotations (custom annotations, view injection)

Source: Internet
Author: User

Note this thing was added in jdk1.5, but his presence was only known because of the view injection using the afinal framework. Always feel that inject special magic, add a sentence can be the corresponding view generated.

Let's get to know the annotations.

First, the relevant knowledge of annotations

Annotations are equivalent to a tag, and in the Javac compiler, development tools and other programs can use reflection to see what tags are on your class and on various elements, and to do the right thing if you have any marks. Tags can be added to packages, classes, fields, methods, method parameters, and local variables.

1, Yuan Annotation: The role is responsible for annotating other annotations. Java5.0 defines 4 standard meta-annotation types, which are used to provide descriptions of other annotation types

@Target: Used to describe the scope of use of annotations (that is, where the annotations described can be used)

The ElementType parameters are:

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 methods

5) Package: Used to describe packages

6) PARAMETER: Used to describe the parameters

7) Type: Used to describe classes, interfaces (including annotation types) or enum declarations

@Retention: Used to describe the life cycle of an annotation (that is, the description of the annotation is valid in what range)
The Retentionpoicy parameters are:

1.SOURCE: Valid in source file (i.e., source file retention)

2.CLASS: Valid in class file (that is, class reserved)

3.RUNTIME: Valid at run time (that is, runtime retention)

@Documented indicates that this annotation is recorded by the Javadoc tool and is not Javadoc annotated by default. That is, when the annotation @documented is declared, the annotation type information is generated in the document

@Inherited indicates that the annotated class inherits automatically: All properties and methods in the annotation class inherit from the Quilt class

Ii. Custom Annotations

Syntax: public @interface annotation name {definition body}

Annotation Method Parameter requirements:
1) can only be modified with the public or default access rights
2) 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.

3) If there is only one parameter member, it is best to set the parameter name to "value"

4) The annotation element must have a definite value. You can specify it in the default value of the definition annotation, or when using annotations. such as: String OnClick () default "";

The code is as follows:

Defining annotations

1 @Target (Elementtype.field) 2 @Retention (retentionpolicy.runtime) 3 @Documented 4  public @Interface  findviewbyidannotation {56     int default 0; 7     default ""; 8 9 }

Using annotations

1 @FindContentViewAnnotation (r.layout.activity_annotation)2  Public classAnnotationactivityextendsActivity {3 4@FindViewByIdAnnotation (id = r.id.tvshow, OnClick = "Onclickshow"))5     PrivateTextView tvShow;6 7@FindViewByIdAnnotation (id = r.id.tvhello, OnClick = "Onclickhello"))8     PrivateTextView Tvhello;9 Ten @Override One     protected voidonCreate (Bundle savedinstancestate) { A         Super. OnCreate (savedinstancestate); -Findviewutil.initview ( This); -     } the  -      Public voidonclickshow () { -Toast.maketext (Getapplicationcontext (), "Show Mr-mo", Toast.length_short). Show (); -     } +      Public voidOnclickhello () { -Toast.maketext (Getapplicationcontext (), "Hello Mr-mo", Toast.length_short). Show (); +     } A}

Third, the annotation processor

Annotations are basically equivalent to annotations if you do not write a note processor. So a note processor is generally written. Findviewutil:

1  Public classFindviewutil {2 3     PrivateFindviewutil () {4     }5 6      Public Static voidInitview (Object object) {7 Initcontentview (object);8 Initcomponentview (object);9     }Ten  One     /** A * Initialize Setcontentview resource layout -      * -      * @paramObject the      */ -     Private Static voidInitcontentview (Object object) { -Class Clazz =Object.getclass (); -Findcontentviewannotation Contentview = (findcontentviewannotation) clazz.getannotation (FindContentViewAnnotation.class); +         if(Contentview! =NULL) { -             Try { +                 intResId =Contentview.value (); A //Activity.setcontentview (resId); atMethod Setcontentviewmethod = Clazz.getmethod ("Setcontentview",int.class); - Setcontentviewmethod.invoke (object, resId); -  -}Catch(Exception e) { - e.printstacktrace (); -             } in         } -     } to  +     /** - * Initialize the control the      * *      * @paramObject $      */Panax Notoginseng     Private Static voidInitcomponentview (FinalObject Object) { -         Try { the             FinalClass Clazz =Object.getclass (); +field[] Fields =clazz.getdeclaredfields (); A              for(Field field:fields) { theFindviewbyidannotation viewbyidannotation = field.getannotation (findviewbyidannotation.class); +                 if(Viewbyidannotation! =NULL) { -                     intResId =viewbyidannotation.id (); $                     FinalString OnClick =Viewbyidannotation.onclick (); $ Object view; -                     if(ObjectinstanceofFragment) { -Method Getviewmethod = Clazz.getmethod ("GetView"); theView Rootview =(View) Getviewmethod.invoke (object); -View =Rootview.findviewbyid (resId);Wuyi}Else { theMethod Findviewbyidmethod = Clazz.getmethod ("Findviewbyid",int.class); -View =Findviewbyidmethod.invoke (object, resId); Wu                     } -  AboutField.setaccessible (true); $ Field.set (object, view); -  -                     if(OnClick! =NULL&& Onclick.trim (). Length () > 0) { -Object Objectfield =Field.get (object); A                         if(ObjectfieldinstanceofView) { +                             FinalMethod Onclickmethod =Clazz.getmethod (OnClick); theView ViewItem =(View) Objectfield; -Viewitem.setonclicklistener (NewView.onclicklistener () { $ @Override the                                  Public voidOnClick (View v) { the                                     Try { theOnclickmethod.setaccessible (true); the Onclickmethod.invoke (object); -}Catch(Exception e) { in e.printstacktrace (); the                                     } the                                 } About                             }); the                         } the                     } the                 } +             } -}Catch(Exception e) { the e.printstacktrace ();Bayi         } the     } the  -}

This is the entire procedure for customizing annotations, which can be done with the view injection function.

This part of the knowledge is summarized from: http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html

Java Annotations (custom annotations, view injection)

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.