Transferred from: http://www.2cto.com/kf/201405/302998.html
This article mainly explains the function of annotation implementation Findviewbyid, first of all, we are familiar with how to define a note in Java and parse an annotation
The concept of annotations is presented in jdk5.0, with three annotations defined in the Java.lang package: override,deprecated,suppresswarnings
Override believes that you are very familiar with this method is to rewrite the method of the parent class
Deprecated indicates that this method or property is not recommended in the new version of the JDK
Suppresswarning is blocking out some warnings.
Once we know the concept of annotations, we come from defining annotations
The definition of annotations is very similar to the interface interface, and there is one more in front of the interface
public @interface testperson{}
Do not take the front of the @ sign off, lost it became the definition of the interface, the above is a definition of the simplest annotations, of course, annotations and classes, can also define attributes, as follows:
public @Interface testperson{ //name is both a property of this annotation and a method of annotation, calling name () The return value is name default Gavin;}
I now want to define two annotations, one annotation to illustrate the meaning of a class, and another to illustrate who tests a method in a class for accountability, as defined below:
// used to label a class for what ? public @Interface classfunction{ default// The method used to label the class is the public who tested it @interface testperson{ // The name is a property rather than a method, and Gavin is its default value, which can be defined without default Gavin
So how do you qualify an annotation to be used on a class or on a method? For example, override is the annotation used in the method, deprecated can be used either on the method or on the class, we can see directly how override is implemented.
@Target (Elementtype.method) @Retention (Retentionpolicy.source) public @Interface Override {} @Documented @retention (retentionpolicy.runtime) @Target (value ={CONSTRUCTOR, FIELD, local_variable, METHOD, Package, PARAMETER, TYPE}) public @Interface Deprecated {}
We find that both annotations use other annotations in the process of definition, such as target and retention, which are called meta-annotations, so let's see what they mean.
The function of the target annotation is to indicate where you are using the annotation, and its value is an enumerated type.
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
The function of the retention annotation is about the life cycle of your annotations, that is, when it expires, and its values are as follows
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)
I would like to introduce the two meta-annotations, other feelings also use is not a lot, if you are interested in Google for a bit
So let's just refine our own annotations.
@Target (Elementtype.method)//Acting on Methods@Retention (Retentionpolicy.runtime)//valid at run time (that is, run-time retention) Public@Interfacetestperson{//name is a property rather than a method, and Gavin is its default value, which can be defined without the default value given.String name ()defaultGavin;} @Target (Elementtype.type)//acting on the class@Retention (Retentionpolicy.runtime)//valid at run time (that is, run-time retention) Public@Interfaceclassfunction{String value ()default ;}
So let's just use our annotations.
@ClassFunction (used to describe a person's basic information) Public class person{ privatestaticfinal String TAG = person ; @TestPerson (Name=JJ) publicvoid setName () { }}
One point to note is that if an annotation property uses value as the value in Classfunction, then the assignment can be @classfunction directly (to describe a person's basic information), but if you are using a different name, Then you must @testperson (NAME=JJ) so call
The above is the process of defining an annotation, let's parse an annotation
Define a Testperson annotation
/**@author Yuanzeyao */@Target (Elementtype.method) @Retention ( Retentionpolicy.runtime) public @Interface Testperson { String name ();}
Then add annotations to the person class
Public class Person { privatestaticfinal String TAG = person ; @TestPerson (Name=Gavin) publicvoid getName () { }}
Parsing annotations
Public classMain {Private Static FinalString TAG =Main; Public Static voidMain (string[] args) { person person=NewPerson (); //get the class for personClass<person> Clazz=person.class; Try { //Find the GetName methodMethod Method=clazz.getmethod (GetName,NULL); //determine if Testperson is labeled if(Method.isannotationpresent (Testperson.class)) { //calling the GetName methodMethod.invoke (Person,NULL); //get an example of Testperson annotationsTestperson test=method.getannotation (Testperson.class); //get its Name propertyString name=Test.name (); System.out.println ( ThisMethod is Test by-->+name); } } Catch(SecurityException e) {}Catch(Nosuchmethodexception e) {}Catch(IllegalArgumentException e) {}Catch(Illegalaccessexception e) {}Catch(InvocationTargetException e) {} }}
already explained the definition annotations and parsing annotations, the following is a concrete analysis of how the use annotations instead of Findviewbyid in Android
Define an annotation
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @Interface injectview { //ID is the control ID, and its ID is annotated with annotations on a control int default -1;}
Add Annotations to activity
Public classMainactivityextendsActivity { Public Static FinalString tag=mainactivity; //ID of the callout textview@InjectView (id=r.id.tv_img)PrivateTextView MText; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Try{Autoinjectallfield ( This); } Catch(Illegalaccessexception e) {}Catch(IllegalArgumentException e) {}if(mtext!=NULL) Mtext.settext (Hello Gavin); } Public voidAutoinjectallfield (activity activity)throwsillegalaccessexception, illegalargumentexception {//get the class that the activity corresponds toClass clazz= This. GetClass (); //get all fields of the activityField []fields=Clazz.getdeclaredfields (); LOG.V (TAG, fields size-->+fields.length); for(Field field:fields) {//Determine if a field is labeled Injectview if(Field.isannotationpresent (Injectview.class) {LOG.V (TAG, is Injectview); //if it's labeled, get its ID .Injectview inject=field.getannotation (Injectview.class); intId=inject.id (); LOG.V (TAG, id--->+ID); if(id>0) { //reflecting access to private members, you must add this sentenceField.setaccessible (true); //and then copy this property toField.set (activity, Activity.findviewbyid (ID)); } } } } }