Java Reflection Best Practices – code farming network

Source: Internet
Author: User
Tags gettext notification center

Reference from

Http://www.cnblogs.com/tianzhijiexian/p/3906774.html
Https://github.com/tianzhijiexian/HttpAnnotation/blob/master/lib/src/main/java/kale/net/http/util/HttpReqAdapter.java

Original webpage address: http://www.codeceo.com/article/java-reflector.html ...

Summary: The simplest and most elegant use of reflection.

Examples of this article can be seen in the sample code and downloaded, if you like star, if you feel there is a mistake please submit issue, if you have a better idea can submit pull request. The sample code for this article is written primarily on joor lines, and if you want to learn more, check out the test code here.

First, the demand

Today, a "lazy" programmer suddenly ran over and said: "Reflection good trouble, I have to ask for some demand." ”

After hearing this sentence, I know that today must be a difficult day, the demand for wonderful flowers came again.

We wrote the reflection before:

 Public Static<T>T Create (HttpRequest httprequest) {Object httprequestentity=NULL; Try{Class<T> httprequestentitycls = (class<t>) class.forname (Httpprocessor.package_name + "." +httpprocessor.class_name); Constructor Con= Httprequestentitycls.getconstructor (HttpRequest.class); Httprequestentity=con.newinstance (HttpRequest); } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); }        return(T) httprequestentity; }

Because reflection is seldom used in development (for common business development), it is used only when writing frames and annotation frames, so it is always unfamiliar to the API. Every time to use the API to go online to check, and then have to experiment with their own, very uncomfortable. Worse, the readability is very poor. I don't want to write this reflection, I hope the reflection can be like

String str = new string ();

So simple, a line of code to do ! .

In addition, many people say that reflection affects performance, and in the development of the need to avoid using reflection. So when is it time to use reflection, and when does it need to be reflected? In what way to avoid reflection? If you do not understand when to use reflection , it is difficult to ingenious the reflection.

Second, analysis

When we received the above demand, I took a sigh of relief, because this time the demand is relatively simple.

I believe that some people will say: "Reflection on those API, has not changed, you will not go to check ah, feel trouble do not write code ah, do not know the internal details of reflection how do you improve it?" ”
In fact, it's completely irrelevant to repeat the trouble-writing code and improve your own code, and I don't know what we've learned since we've written thousands of lines findviewById , in addition to knowing the class and the XML file bindings.

So this time we continue to challenge traditional thinking and templating code to see how the new generation of reflection code should be written, and how to use a line of code to reflect the class.
Before you do, come and see what we usually do with reflection?

1. 反射构建出无法直接访问的类 

2. set或get到无法访问的类变量 

3. 调用不可访问的方法

III. Solution 3.1 A line of code write reflection

As an Android programmer, simply take TextView this kind of surgery. First define a class variable:

TextView MTv;

To get an instance by reflection:

There are parameters to establish the class MTV = Reflect.on (Textview.class). Create (this).//Get class String Word = Reflect.on ("Java.lang.String") by class name . Create ("Reflect TextView"). get ();//no parameters, establish class fragment fragment = Reflect.on (Fragment.class). Create (). get ();

To invoke a method by reflection:

Call the parameterless method L.D ("Calling GetText ():" + Reflect.on (MTV). Call ("GetText"). toString ());//Invoke Parameter Method Reflect.on (MTV). SetTextColor ", 0xffff0000);

By reflecting get, set class variables

There is a Mtext variable in the TextView to see how we approach it.

Set the parameter Reflect.on (MTV). Set ("MText", "----------new Reflect TextView----------");//Get parameter L.D ("Setgetparam is" + Reflect. On (MTV). Get ("MText"));
3.2 When to use reflection, when not to reflect

It's time to weigh the pros and cons, first of all we make it clear that in the daily development try not to use reflection, unless you encounter a method that must be called through reflection. For example, I encountered this situation when I was doing a drop-down Notification center feature. The system does not provide an API, so we can only call through reflection, so I wrote this code myself:

<uses-permission android:name= "Android.permission.EXPAND_STATUS_BAR"/>Private Static voidDoinstatusbar (Context mcontext, String methodName) {Try{Object service= Mcontext.getsystemservice ("StatusBar"); Method Expand=Service.getclass (). GetMethod (MethodName);        Expand.invoke (service); } Catch(Exception e) {e.printstacktrace (); }    }    /*** Display Message Center*/     Public Static voidOpenstatusbar (Context mcontext) {//determine the system version numberString methodName = (VERSION. Sdk_int <= 16)? "Expand": "Expandnotificationspanel";    Doinstatusbar (Mcontext, methodName); }    /*** Close Message Center*/     Public Static voidClosestatusbar (Context mcontext) {//determine the system version numberString methodName = (VERSION. Sdk_int <= 16)? "Collapse": "Collapsepanels";    Doinstatusbar (Mcontext, methodName); }

Let's take a look at how doInStatusBar simple it is to write with Joor:

Private Static void Doinstatusbar (Context mcontext, String methodName) {        = Mcontext.getsystemservice ("StatusBar");        Reflect.on (Service). Call (MethodName);    }

Wow, just a line of code ah, very cool ~

When you're finished, let's take a look at the reflection problem. Because it is not the system to give the API, so Google in different versions of the different method name to do the processing, with reflection we have to make version of the judgment, it is important to note, in addition to reflection in the performance is really bad, here need to be cautious.

My advice:

If there are many places in a class that are private, and your needs depend on these methods or variables, then it is better to copy this class into your own class, such as toolbar, than to use reflection.

When we write the frame, we will definitely use the reflection, very simple example is the event bus and annotation framework, Xiang Brother said a word: no reflection, no frame . It is also because of the framework of their own writing, so the method name and parameters called by reflection will not change, let alone do the runtime annotation framework, the reflection will definitely appear. In this case do not be afraid of reflection, simply feel free to do it boldly. Because it will allow you to accomplish a lot of impossible tasks.

The summary is:

The actual daily development of the time to minimize the use of reflection, you can copy the form of the original class to avoid reflection. When writing a frame, do not shy of reflection, in the key to use reflection to help themselves.

Iv. PostScript

We finally finished writing the reflection in one line of code, avoiding a lot of meaningless template-style code. Need to explain again, this article is based on Joor to write, here is the original project readme Chinese translation.

Joor is the open source library that I accidentally met, I knew this was what I wanted the first time I saw it, because I was so confused when I was being reflected, and its concise coding method brought me new thinking, which greatly improved the readability of the code. By the way, the author is better (is not willing to let me into the Chinese readme), technology is also very good. The project has a very detailed test case, and several similar reflection call wrapper libraries are also given. It can be seen that the author has done a lot of research and testing work in writing the library, so that we could use the library safely (in fact, two classes).

This article hopes to bring everyone a new idea of reflection, give a most simple and practical reflection, hope can be quickly applied to practice. More importantly, through the analysis of the Joor, let me know that the library should be investigated before writing a similar library, rather than completely create new wheels, research and testing is the important guarantee of code stability.

Java Reflection Best Practices – code farming network

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.