Android injection framework everything you should know ------ build your own injection framework, android ------

Source: Internet
Author: User

Android injection framework everything you should know ------ build your own injection framework, android ------
Preface

All Java frameworks are reflection-based, so there is a saying that there is no reflection or framework. Therefore, the Android injection framework is also reflection-based. Next we will briefly introduce everything you should know about the Android injection framework.

Description

Annotation (Annotation) is a very important part in Java, but it is usually seldom used. Here is a simple one. Now we can simply write an annotation and then explain it.
Right-click Eclipse-> New-> Annotation and type the following code.

@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface TestAnnotation{    int vauls();    String test();}

We can see that the Target annotation is defined as the FIELD in the class, and the Retention annotation is the runtime annotation. You can take a look at the meaning of each annotation. Then let's see how we use this annotation. We declare an object in a class. As follows:

    @TestAnnotation(test="hello",vauls=12)    private Button button3;

In this way, our annotations are declared. Then there is the use of annotations. Also, let's take a simple look at how to use it.

Class <?> Clas = getClass (); // obtain the attribute Field fields [] = clas. getDeclaredFields (); for (Field field: fields) {// obtain the annotation TestAnnotation testAnnotation = field. getAnnotation (TestAnnotation. class); if (testAnnotation! = Null) {// obtain the value String test = testAnnotation in the annotation. test (); int id = testAnnotation. vauls (); System. out. println (test + id );}}

In this simple way, if you need to understand the annotation in depth, you can check the annotation information.

About the injection framework, you should know everything to build your own injection framework.

First, let's talk about what we want to implement this time, inject the View and the Onclick event. First, let's solve the problem of injecting the View.

View Injection

First, we will create a new annotation and input the following code.

Package com. edsheng. inject; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/*** Copyright (c) 2015, TNT All Rights Reserved. * The View annotation can be annotated when the VIew control is declared * @ author bobo * @ date 2015-6-9 * @ filename ViewInject. java **/@ Target (ElementType. FIELD) @ Retention (RetentionPolicy. RUNTIME) public @ interface ViewInject {int value ();}

Then we create a new ViewInjectUtile class and implement this method in it.

/*** Injection control View ** briefly describes the process of the injection control. * 1: traverse all the fileds Based on the Filed. * 2: Get the annotation we need. * 3: get id * 4 Based on annotation: Call the lookup method through reflection * 5: assign a value through reflection ** @ param activity */private static void injectView (Activity activity) {Class <?> Cls = activity. getClass (); Field field [] = cls. getDeclaredFields (); // obtain all filed for (Field field2: field) {ViewInject inject = field2.getAnnotation (ViewInject. class); // obtain the annotation if (inject! = Null) {int id = inject. value (); // obtain the id try {// findViewById Method = cls. getMethod ("findViewById", int. class); Object resView = method. invoke (activity, id); // obtain the control field2.setAccessible (true); field2.set (activity, resView); // assign the value to View} catch (Exception e) {e. printStackTrace ();}}}}

The comments are clearly written and I will not explain it. In this way, we can easily implement View injection and use.

Event Injection

We also created a new annotation to complete event injection and typed the following code.

/***** Copyright (c) 2015, TNT All Rights Reserved. * The annotation class of the method can be annotated when OnlickLisenler needs to be called back. ** @ author bobo * @ date 2015-6-9 * @ filename MethodInject. java **/@ Target (ElementType. METHOD) @ Retention (RetentionPolicy. RUNTIME) public @ interface MethodInject {int [] value ();}

Then implement this method in the ViewInjectUtile class.

/*** Injection listening method all the frameworks are basically implemented based on reflection. Isn't there a single sentence? No reflection, no frame. * Simply put, this process * 1: inject Method * 2 in our acitvity: generate dynamic proxy * 3: call back our injection method through the East dynamic proxy ** @ param activity */private static void injectMethod (Activity activity) {Class <?> Cls = activity. getClass (); Method methods [] = cls. getMethods (); // obtain the public Method of this class for (method: methods) {MethodInject meathdInject = Method. getAnnotation (MethodInject. class); // obtain the annotation if (meathdInject! = Null) {// generate a dynamic proxy Object Proxy when there is an annotation = (Object) proxy. newProxyInstance (View. OnClickListener. class. getClassLoader (), new Class <?> [] {View. onClickListener. class}, new DynaHanlder (activity, method); int ids [] = meathdInject. value (); // obtain the id try {Method findviewbyid = cls. getMethod ("findViewById", int. class); // obtain the method for (int id: ids) {Object view = findviewbyid. invoke (activity, id); // obtain view Method onclickMethod = view by Method. getClass (). getMethod ("setOnClickListener", View. onClickListener. class); onclickMethod. invoke (view, proxy); // call the setOnClickListener method to callback in the dynamic class} catch (Exception e) {e. printStackTrace ();}}}}

Here, we need to pay attention to the generation and proxy of dynamic classes. We call the View. OnClickListener interface back and forth to the annotation through proxy and reflection. Let's see how this DynaHanlder is implemented.

Public static class DynaHanlder implements InvocationHandler {Object target = null; Method method = null; public DynaHanlder (Object target, Method method) {super (); this.tar get = target; this. method = method;}/*** this function is the callback Method for Dynamic Registration */@ Override public Object invoke (Object proxy, method, Object [] args) throws Throwable {// call the Dynamic Injection Method return this. method. invoke (target, args );}}

That is, it is very easy to keep our method application. When we call us through proxy callback, we also call our method through reflection.
Finally, an interface method is exposed to the outside.

// External call interface static public void inject (Activity activity) {injectView (activity); injectMethod (activity );}

Finally, let's see how we use it.

public class MainActivity extends Activity{    @ViewInject(R.id.button)    private Button button;    @ViewInject(R.id.button2)    private Button button2;    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.mainactivity);        ViewInjectUtile.inject(this);        button.setText("fuck");        button2.setText("asdfasdf");    }    @MethodInject({ R.id.button, R.id.button2 })    public void onClick(View v)    {        switch (v.getId())        {        case R.id.button:            // System.out.println("asdfasdf");            Toast.makeText(this, "R.id.button", 0).show();            break;        case R.id.button2:            Toast.makeText(this, "R.id.button2", 0).show();            // System.out.println("asdf");            break;        default:            break;        }    }

When you click the button, the system calls back our method and binds the id and control from the very beginning. This is the essence of the injection framework, you need to complete a better and more powerful framework on your own. Paste the Source Code address here: Portal

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.