Analysis and use of Android Annotation annotations

Source: Internet
Author: User

Analysis and use of Android Annotation annotations

It is said that the application of Annotation is very simple, but sometimes we don't know where to start when we really need to implement it. Why do we think it is very simple, but we cannot start it?
There is only one reason. We use very few of them, but for those who write the framework, Annotation is frequently used. Since we usually use a very small amount of resources, it makes no sense for me to write this blog. Indeed, I just want to give you a reference document. However, I still hope that you can use this blog to enhance your understanding of Annotation. This blog saves unnecessary knowledge points of Annotation, just as MOOC said, learning only useful.
Enter the topic:
I. Analyze the source code first:
You only need to know the four classes.
1,

  @Documented  @Retention(RetentionPolicy.RUNTIME)  @Target(ElementType.ANNOTATION_TYPE)  public @interface Retention {      RetentionPolicy value();  }

The purpose of this Annotation is to set the value when we need to declare a custom Annotation, when talking about the second class, you can refer to this class and add @ Retention (RetentionPolicy) directly to the custom Annotation. RUNTIME) or @ Retention (value = RetentionPolicy. RUNTIME). The effect is the same. Here, you must note that Annotation can be annotated by yourself.
2,

  public enum RetentionPolicy {      /**       * Annotation is only available in the source code.       */      SOURCE,      /**       * Annotation is available in the source code and in the class file, but not       * at runtime. This is the default policy.       */      CLASS,      /**       * Annotation is available in the source code, the class file and is       * available at runtime.       */      RUNTIME  }

This is an enumeration type. The function is to control the Annotation level. The higher the value, the higher the permission, and the greater the scope of Annotation. The following describes the scopes of the three levels:
SOURCE: valid only in the SOURCE object Annotation, that is, as long as the code has been compiled, the Annotation with the permission declared as SOURCE is invalid;
CLASS: the file or code has been compiled, which is still valid at this time. When the code runs, it will be ineffective;
RUNTIME: This is equivalent to the maximum permission. Remember that it can be used at any time. When writing code, we all want to use it at RUNTIME. Therefore, we generally declare it as the RUNTIME permission.

3,

  @Documented  @Retention(RetentionPolicy.RUNTIME)  @Target(ElementType.ANNOTATION_TYPE)  public @interface Target {      ElementType[] value();  }

This is also an Annotation class. The function of this class is declared when we customize Annotation, and then determine where the role type of the custom Annotation is, its value is what the next class will talk about. Its usage is the same as the Retention Annotation. Specifically, all Annotation is used in this way.
4,

  public enum ElementType {      /**       * Class, interface or enum declaration.       */      TYPE,      /**       * Field declaration.       */      FIELD,      /**       * Method declaration.       */      METHOD,      /**       * Parameter declaration.       */      PARAMETER,      /**       * Constructor declaration.       */      CONSTRUCTOR,      /**       * Local variable declaration.       */      LOCAL_VARIABLE,      /**       * Annotation type declaration.       */      ANNOTATION_TYPE,      /**       * Package declaration.       */      PACKAGE  }

This class is used to determine the location of Annotation. Different values have different positions.
/**
* Applies to classes, interfaces, or enumeration
*/
TYPE,
/**
* Applies to fields, that is, member variables.
*/
FIELD,
/**
* Method.
*/
METHOD,
/**
* Parameter.
*/
PARAMETER,
/**
* Constructor.
*/
CONSTRUCTOR,
/**
* Local variable.
*/
LOCAL_VARIABLE,
/**
* Annotation.
*/
ANNOTATION_TYPE,
/**
* Package name.
*/
PACKAGE
I just translated it in English. please correct me if you have any mistakes.
After the basic usage is introduced, start customizing Annotation.
Ii. Custom Annotation
You can use Android studio to create an Annotation class and specify the Annotation type directly when creating the class. The created file is as follows:

  /**   * Created by moon.zhong on 2015/2/14.   */  public @interface TestAnnotation {  }

It is very similar to the interface, but there is only one more @. As mentioned above, you need to add @ Retention (RetentionPolicy. RUNTIME) to determine the permission size. Here, the maximum permission is used directly, and the type of the role is specified @ Target (ElementType. METHOD ).
The custom Annotation is complete.

3. Use Annotation
Writing any code is not used for reading, so we must know how to use it.
Annotation is often used in combination with reflection. When we learn reflection, we know that many methods in reflection can obtain Annotation values, when Annotation is used, reflection is basically used. We often say that there is no reflection and no framework. This is why Annotation is widely used in most frameworks.
Here we also use the reflected column to describe the use of Annotation.
Write a custom Annotation so that it can be applied to the class,

  /**   * Created by moon.zhong on 2015/2/14.   */  @Retention(value = RetentionPolicy.RUNTIME)  @Target(value = ElementType.TYPE)  public @interface ClassAnnotation {  }

Define a Bean class and add annotations.

  /**   * Created by moon.zhong on 2015/2/14.   */  @ClassAnnotation  public class Bean {  }

Check whether the annotation can be used normally through reflection

  public class MainActivity extends ActionBarActivity {      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          Class
   mClass = Bean.class ;          Annotation annotation[] = mClass.getAnnotations() ;          for (Annotation a : annotation){              Log.v("zgy","====getAnnotations===="+a.annotationType()) ;          }      }  }

Last printed log information: zgy :=== getAnnotations === interface moon. annotationdemo. ClassAnnotation

Let's take a look at how to set a value for a custom Annotation, which can be followed by a value like @ Retention (RetentionPolicy. RUNTIME. When you read the log information above, did you find that an interface is printed more, and the full name of Annotation follows? In fact, Annotation is an interface in this province, therefore, when declaring a variable, you only need to define an abstract method without implementation. You can refer to public @ interface Retention.

  /**   * Created by moon.zhong on 2015/2/14.   */  @Retention(value = RetentionPolicy.RUNTIME)  @Target(value = ElementType.TYPE)  public @interface ClassAnnotation {      String print() ;  }www.bkjia.com  /**   * Created by moon.zhong on 2015/2/14.   */  @ClassAnnotation(print = "annotation")  public class Bean {  }

The same is true for @ interface Retention. Add @ ClassAnnotation (print = "annotation") to the Bean class name. Note that, it cannot be written as @ ClassAnnotation ("annotation"), because the defined method here is print (). If it is changed to value (), it can be omitted.

    /**     * Created by moon.zhong on 2015/2/14.     */    @Retention(value = RetentionPolicy.RUNTIME)    @Target(value = ElementType.TYPE)    public @interface ClassAnnotation {        String value() ;    }    /**     * Created by moon.zhong on 2015/2/14.     */    @ClassAnnotation("annotation")    public class Bean {    }
For (Annotation a: annotation) {Log. v ("zgy", "=== print ===" + (ClassAnnotation) ). print () ;}print log information zgy :=== print === annotation indicates that we have obtained the set value, then what functions should be implemented depends on everyone's wisdom.

Iv. Summary:
The old rule is like pouring juice at the end of cooking. Here we will make a summary. When defining Annotation, pay attention to two points. 1. @ Retention (RetentionPolicy. RUNTIME) Annotation to determine the role permission of the declared Annotation. Here it is generally set to the maximum; 2. Through @ Target (ElementType. ANNOTATION_TYPE) annotation to determine who the annotation is intended. Note that the custom Annotation defines an abstract method. If the abstract method is named value, it can be omitted when it is used. Otherwise, it cannot be omitted. For personal suggestions, add them.

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.