Android Injection Framework Everything you should know--build your own injection framework

Source: Internet
Author: User
Tags call back

All of Java's frames are basically reflection-based, so there's a saying, no reflection, no frame. So the Android injection framework is also based on reflection, and the next step is simply to introduce the Android injection framework that you should know. Introduction to Annotations

Annotations (Annotation) are a relatively important part of Java, but they are rarely touched by this part, so it's a simple one. Now let's simply write an annotation and explain it.


Right-->new->annotation through eclipse and then typing the following code.

@Target (Elementtype.field) @Retention (retentionpolicy.runtime)@interfaceTestAnnotation {int Vauls (); String test ();
You can see that the target label we defined as field is the meaning of the attribute within the class, and retention this callout is the annotation that represents the runtime. The meaning of each note you can take a look at yourself. Then see how we use this annotation. We arbitrarily declare an object within a class. As follows
@TestAnnotation (test= "Hello", vauls=12)private Button Button3;

This gives us a good statement of our annotations. Then there is the use of annotations. It's also easy to see how to use it.

Class<?> Clas =getclass ();//Get PropertiesField fields[] =clas.getdeclaredfields (); for(Field field:fields) {//Get AnnotationsTestannotation testannotation = field.getannotation (testannotation.class); if(Testannotation! =NULL) {      //get the value inside the noteString test =testannotation.test (); intID =Testannotation.vauls (); SYSTEM.OUT.PRINTLN (Test+ID); }}

For this simple use, if you need to understand the annotations in depth, you can check the information of the annotations.

everything you should know about the injection framework build your own injection framework

First of all, let's talk about what we are going to do this time, inject view and inject the OnClick event, first we solve the problem of injecting view.

The injection of view

Let's start by creating a new annotation and typing the following code.

 PackageCom.edsheng.inject;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/*** * Copyright (c), TNT All rights reserved.* view annotations when declaring the view control .@authorbobo* @date 2015-6-9* @filename viewinject.java**/@Target (Elementtype.field) @Retention (retentionpolicy.runtime) Public@interfaceViewInject {intvalue ();}

Then we are creating a new Viewinjectutile class that implements such a method inside.

/*** * Inject control view* simply say the flow of the injected control * 1: According to filed traverse all filed* 2: Get the annotations we need * 3: According to the annotations to get id* 4: By Reflection to call search method * 5: Finally by reflection assignment *@paramActivity*/PrivateStaticvoidinjectview (activity activity) {Class<?> CLS =Activity.getclass (); Field field[]= Cls.getdeclaredfields ();//get all the filed for(Field Field2:field) {Viewinject inject= Field2.getannotation (viewinject.class);//Get Annotationsif(Inject! =NULL) {intid = inject.value ();//Get IDTry {   //Findviewbyidmethod = Cls.getmethod ("Findviewbyid",int.class); Object Resview= Method.invoke (activity, id);//Get ControlField2.setaccessible (true); Field2.set (activity, resview);//assigning values to a view}Catch(Exception e) {e.printstacktrace (); }}}}

The comments are written very clearly I will not explain, so it is very simple to realize the injection of view, the use is very simple.

Injection of events

Let's create a new annotation to complete our event injection, typing the following code.

/**@author  bobo* @date 2015-6-9* @filename methodinject.java**/@Target (Elementtype.method) @Retention (retentionpolicy.runtime) public @interfaceMethodInject { int [] Value ();}

Then implement such a method within the Viewinjectutile class.

/*** Injection monitoring method All the frames are basically based on reflection, do not have a word? No reflection no frame. * Simply say this process * 1: Inject method in our acitvity * 2: Generate dynamic Proxy * 3: Go back to the method we injected by the East dynamic Agent * *@paramActivity*/PrivateStaticvoidinjectmethod (activity activity) {Class<?> CLS =Activity.getclass (); Method methods[]= Cls.getmethods ();//get the public method for this class for(Method method:methods) {methodinject meathdinject= Method.getannotation (methodinject.class);//get Annotations on a method  if(Meathdinject! =NULL) {     //generate dynamic proxies when annotations are availableObject proxy = (object) proxy.newproxyinstance (View.onclicklistener.class. getClassLoader (), newclass<?>[] {view.onclicklistener.class}, Newdynahanlder (activity, method)); intIds[] = Meathdinject.value ();//get the ID inside the note     Try{Method Findviewbyid= Cls.getmethod ("Findviewbyid",int.class);//Get the method         for(intid:ids) {Object View= Findviewbyid.invoke (activity, id);//get view based on methodMethod Onclickmethod = View.getclass (). GetMethod ("Setonclicklistener", View.onclicklistener.class); Onclickmethod.invoke (view, proxy);//Call the Setonclicklistener method callback inside the dynamic class        }     }     Catch(Exception e) {e.printstacktrace (); }  }}}

It is important to note that the dynamic class generation and proxy, we put view.onclicklistener this interface through the proxy and reflection to the annotation to the place, we see how this dynahanlder implementation.

publicstaticclassdynahanlder Implementsinvocationhandler {Object target=NULL; Method Method=NULL; PublicDynahanlder (Object target, method) {Super();  This. target =Target;  This. method =method;}/*** This function is a callback method for dynamic registration*/@OverridepublicObject Invoke (Object Proxy, Method method, object[] args)throwsThrowable {//here's how to invoke the dynamic injection   return  This. Method.invoke (target, args);}}

It is also very simple to keep the application of our method when we are called back through the proxy we also call our method by reflection.


Finally, an interface method is exposed to the outside.

// External Call Interface Static  Public void inject (activity activity) {   Injectview (activity);   Injectmethod (activity);}
 Public classMainactivityextendsActivity {@ViewInject (R.id.button)Privatebutton button; @ViewInject (R.id.button2)PrivateButton button2; @Overrideprotected voidonCreate (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 voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.button://System.out.println ("asdfasdf");Toast.maketext ( This, "R.id.button", 0). Show ();  Break;  CaseR.id.button2:toast.maketext ( This, "R.id.button2", 0). Show (); //System.out.println ("asdf");             Break; default:             Break; }}

When the click button will call back our method, injected in the beginning to help us complete the ID and control binding, this is the main essence of the injection framework, the need for a better and more powerful framework needs to be done slowly.

Android Injection Framework Everything you should know--build your own injection framework

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.