Explanation of the annotation mechanism of the fastest development framework XUtils of Android, androidxutils

Source: Internet
Author: User

Explanation of the annotation mechanism of the fastest development framework XUtils of Android, androidxutils

In the previous article, XUtils, the most popular development framework of Android, briefly introduced the basic usage of xUtils. This article describes the annotation principles in xUtils.

Let's take a look at the demo code in xUtils:

@ViewInject(R.id.tabhost)    private FragmentTabHost mTabHost;@ViewInject(R.id.big_img)    private ImageView bigImage;

A lot of people may say what this is. In fact, this is the content in Java core. JavaEE should be familiar with it. Like the famous spring framework, a lot of annotations are used. So what is annotation? The following describes Java annotations in detail:

Annotation provides a formal method for us to add information to the code, we can easily use the data at a later time (using the data through parsing annotations). The common functions are as follows:

  • Generate a document. This is the most common and the earliest annotation provided by java. Commonly used include @ see @ param @ return and so on.
  • Tracks code dependencies to replace configuration files. It is common to use annotation-based configuration starting with spring 2.5. The function is to reduce the configuration. The current framework basically uses this configuration to reduce the number of configuration files. Yes
  • Check the format during compilation. For example, if @ override is placed before the method, if your method does not overwrite the superclass method, you can check it during compilation.

PackageJava. lang. annotationContains all the original annotations and interfaces required for custom annotations. For example, java. lang. annotation.AnnotationIt is an interface inherited by all annotations and is automatically inherited. It is specified when no definition is required. It is similar to that where all classes automatically inherit objects.


Java annotations are some meta information appended to the code. They are used for parsing and using some tools during compilation and runtime to provide instructions and configuration functions. Annotations do not and cannot affect the actual logic of the Code. They only play an auxiliary role. Included in the java. lang. annotation package.

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.

1. Metadata Annotation

Meta annotation refers to the annotation of the annotation. There are four types: @ Retention @ Target @ Document @ Inherited.

1.1 @ Retention: defines the annotation Retention policy

@ Retention (RetentionPolicy. SOURCE) // The annotation only exists in the SOURCE code. The class bytecode file does not contain @ Retention (RetentionPolicy. CLASS) // The default Retention policy. The annotation will exist in the class bytecode file, but it cannot get @ Retention (RetentionPolicy. RUNTIME) // annotation will exist in the class bytecode file, which can be obtained through reflection during RUNTIME
1.2 @ Target: define the Target of the Annotation
The source code is defined as @ brief ented.
@ Retention (RetentionPolicy. RUNTIME)
@ Target (ElementType. ANNOTATION_TYPE)
Public @ interface Target {
ElementType [] value ();
}

@ Target (ElementType. TYPE) // interface, class, enumeration, Annotation

@ Target (ElementType. FIELD) // The constant @ Target (ElementType. METHOD) // METHOD @ Target (ElementType. PARAMETER) // method PARAMETER @ Target (ElementType. CONSTRUCTOR) // CONSTRUCTOR @ Target (ElementType. LOCAL_VARIABLE) // local variable @ Target (ElementType. ANNOTATION_TYPE) // annotation @ Target (ElementType. PACKAGE) // @ interface in the PACKAGE is a keyword. When designing annotations, you must define a type as @ interface instead of the class or interface keyword, from the source code above, we can know that there can be multiple elementtypes, and one annotation can be class, method, and field.
1.3, @ Document: indicates that the annotation will be included in javadoc 1.4, @ Inherited: indicates that the subclass can inherit the annotation from the parent class.
2. java annotation Customization
The following is an example of custom annotation.

This annotation defined by @ Retention (RetentionPolicy. RUNTIME) indicates that the annotation will exist in the class bytecode file and can be obtained through reflection during RUNTIME.

@ Target ({ElementType. TYPE, ElementType. METHOD}). Therefore, this annotation can be a class annotation or a METHOD annotation.

This annotation can be customized. Of course, the Members in the annotation can be basic data types, Data, objects, and so on.

After learning about the Java annotation mechanism, let's talk about the annotations used in xUtils and the thinking process:

package com.lidroid.xutils.view.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface ContentView {    int value();}
The above is the ContentView annotation, some declarations and parameters.

 private static void injectObject(Object handler, ViewFinder finder) {        Class<?> handlerType = handler.getClass();        // inject ContentView        ContentView contentView = handlerType.getAnnotation(ContentView.class);        if (contentView != null) {            try {                Method setContentViewMethod = handlerType.getMethod("setContentView", int.class);                setContentViewMethod.invoke(handler, contentView.value());            } catch (Throwable e) {                LogUtils.e(e.getMessage(), e);            }        }}

The above is a static annotation object function in ViewUtils, which uses the ContentView annotation declared above. getAnnotation is the annotation object, and handler is the pointer passed in by our activity, get the handlerType of the Class type (this is the Class) through the pointer. handlerType dynamically loads setContentView through getMethod. setContentView is familiar to all users with the function of loading layout in Android, then we get a Method for reflection to implement function loading.

SetContentViewMethod. invoke (handler, contentView. value (); this sentence can also be understood in this way, that is, handler has the setContentViewMethod method, and the parameter of setContentViewMethod is contentView. value ().

In this way, I understand why.

@ ContentView (R. layout. main)
The public class MyActivity extends FragmentActivity can be used to load the layout. The annotation operations of other xUtils are similar.

The following is a simple flowchart:


If you have any questions, please leave a message and repeat the source.





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.