Java Advanced Annotations, reflections

Source: Internet
Author: User

Java annotations, reflection and other mechanisms to make the dynamic agent possible, generally through the fully qualified name + class name, find the class, you can invoke its construction method and other methods, you can get its parameter (Field) name and value.

Annotations are generally used in code comments, code reviews (there are no standards written, such as inspect), code injection (HOOK,ASBECTJ), and what needs to be considered is when to inject (the compile period also runs)

Reflection is typically used to dynamically convert JSON and object to each other, executing the underlying code, such as setting the accessible of a class to false to prevent others from hook modification

Example: Ali's Fastjson Analysis:

@Override public <T> T json2object (String json, class<t> clazz) {return Json.parseobject (JSON, clazz);} @Override public String Object2json (Object instance) {return json.tojsonstring (instance);}

Example Java's default annotation policy:

public enum Retentionpolicy {    /**     * Annotations is to be discarded by the compiler.
default, compile-time is discarded      */SOURCE,    /**      * Annotationsis to being recorded in the class file by the compiler * and need not being     retained B Y the VM at run time.  This is the default     * behavior.
default is interpreted by the compiler, but discarded at run time      */CLASS,    /**      * Annotationsis to being recorded in the class file by the compiler and     * retained by the VMS at Run time, so they could be read reflectively.      *
       is interpreted at compile time, the runtime is still saved and can be used        directly java.lang.reflect.AnnotatedElement      */ RUNTIME}
Example Hook:

Hook thing seems mysterious, in fact, it is not so difficult, I hope you crossing read this article can have some gains.

This is the hook for Android Click events, that is, the meaning of Onclicklistener,hook is that you can do something else after calling Setonclicklistener, other things you want to do with all the click events, then here, Let me take the burial point as an example.

First to show the effect:

PublicvoidOnClick(ViewView){MapMap=NewHashMap();Switch(View.GetId()){CaseR.Id.Btn_hook1:Map.Put(Basf,Palm);Map.Put(Cuisine,than);Break;Caser..: map. ( "Tf-boys"  "hehe Hey" map. ( "id" break} view. (r. Id.map        

I did three things inside the onclick:

1. New HashMap

2. Map plug you want to bury the data

3. Upload the data to the corresponding view

Then clicking on the button will pop up a toast, such as:

So the interesting place is, we didn't play toast in the Click event, where did the toast come from? Hey, it's a hook, of course.

Hook

Start the hook process below:

The whole process is condensed down to four words-counter switch!

Analyze source code

First of all look at the Android.view.View in the code, Monclicklistener variable quietly here (there are other events oh, such as onlongclicklistener, etc., you can try to hook the next after learning), What we need to do is counter switch, replace the flower with the wood, Monclicklistener is the member variable of Listenerinfo class, and continue to see where listenerinfo is initialized in view. Because the only thing we get is the view object.

Yes, found, Getlistenerinfo () Did this thing, we start with this method to take listenerinfo down, and then counter switch.

The technical solution has already been, then began to start the code.

Realize

The hook process is to take full advantage of the Java reflection mechanism of the process, a few lines of code to do, let's see:

Take the view's class object firstClassClazzview=Class.Forname("Android.view.View");and get the Getlistenerinfo.MethodMethod=Clazzview.Getdeclaredmethod("Getlistenerinfo");Since Getlistenerinfo is not a pulic method, it needs to be modified to be accessiblemethod. (trueclass clazzinfo =  Class. ( "Android.view.view$listenerinfo" field field = clazzinfo getdeclaredfield ( "Monclicklistener" //so here first temporarily stay, we put wood to create good. //dig a pit--and wait to fill in              

Since counter switch has a nature to be able to forget, that is to respect the original type, so we have to implement the Wood View.onclicklistener interface:

PublicStaticClassHooklistenerImplementsView.Onclicklistener{PrivateView.OnclicklistenerMoriginallistener;Directly in the constructor to pass in the original OnclicklistenerPublicHooklistener(View.OnclicklistenerOriginallistener){Moriginallistener=Originallistener;}@OverridePublicvoidOnClick(ViewV){If(Moriginallistener!=Null){Moriginallistener.OnClick(V);}StringBuilderSb=NewStringBuilder();Sb.Append("Hook succeed.\n");Get the parameters passed beforeObjectObj=V.Gettag(R.Id.Id_hook);The following operation can be wretched in order toIf(Obj!=Null&&ObjinstanceofHashMap&&! ((Map)Obj).IsEmpty()){For(Map.Entry<String,String>Entry:((Map<String,String>)Obj).EntrySet()){Sb.Append("Key =").Append(Entry.GetKey()).Append(" ").Append("VALUE =").Append(Entry.GetValue ()) . (} } else {sb.< Span class= "NA" >append ( "params = null\n" } toast. (v. Getcontext (), sb. (), toast.). show (); }             /span>                

The above code is our wood, in order to look more simple, I directly through the constructor of the original flower (Onclicklistener) to pass over, and then in the new Hooklistener onclick () in the original event to continue to complete, and add some things that you want to be wretched.

Then continue filling in the previously buried pits:

field.set(listenerInfo, new HookListener((View.OnClickListener) field.get(listenerInfo)));

The process of the wood to do two things, one is to pass the original onclicklistener to Hooklistener, the second is to replace the new Hooklistener into the listenerinfo,perfect.

At this point, counter switch is finished, simple.

The appropriate call hook

We put the hook method is written, the end is to call you need to hook the view, in most cases, you can put the hook this matter to the base to do, traverse the current Rootview all the view, and then each call hook, the focus of this article is not this, I will not repeat.

Summary

This article just to bury the point as an example, = = Actually I think buried this chestnut is not very good, sister's all passed so many parameters come over, still care to call their own tracker here? No matter, no chestnut will make this hook feel very powerless, I hope that you can see the hooks after the hook no longer crazy, in fact, and custom view as simple.

The sample code has been synced to GitHub, so there's a problem with issue = Https://github.com/JeasonWong/ClickTracker

http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117777
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117890
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117994
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=118376

http://www.woaipu.com/shops/zuzhuan/61406

Java Advanced Annotations, reflections

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.