Example of reflection technology in android

Source: Internet
Author: User

In computer science, reflection is a type of application that can be self-described and self-controlled. That is to say, this type of application uses a mechanism to describe and monitor its own behavior, and according to its own behavior status and results, adjusts or modifies the status and semantics of the behavior described by the application. reflection is one of the characteristics of the Java programming language. It allows running Java programs to check themselves, or "self-Review", and can directly manipulate internal properties of the program. The implementation of the Java reflection mechanism involves four classes: class, Constructor, Field, and Method. The class represents the time class Object and Constructor-class Constructor object, attribute object of Field-class, Method object of Method-class.

1. The reflection technology can be used to access data methods under other packages, which provides convenience for some APK skins.

First initialize skinContext


 try {              skinContext = this.createPackageContext("com.skin",                       CONTEXT_IGNORE_SECURITY|CONTEXT_INCLUDE_CODE);          } catch (NameNotFoundException e) {              // TODO Auto-generated catch block              skinContext=null;              e.printStackTrace();          }  

You can use the following method to access the resource ID under the specified package
/*** Get the ID of all resources of the corresponding package * in MAP * @ param packageName * @ return */private Map
 
  
> GetSkinResourcesId (String packageName) {Map
  
   
Temp = null; Map
   
    
> ResMap = new HashMap
    
     
> (); Try {// obtain the R File Class in the skin package
     RClass = skinContext. getClassLoader (). loadClass (packageName + ". R"); // Class that obtains the IDs of various resources
     [] ResClass = rClass. getClasses (); String className, resourceName; int resourceId = 0; for (int I = 0; I
     
      
(); Temp. put (resourceName, resourceId); Log. I ("DDDDD", "className:" + className + "resourceName:" + resourceName + "" + "resourceId:" + Integer. toHexString (resourceId) ;}// the className should be com. skin. r$ layout form // cut off the previous package name and. r$ to facilitate the use of className = className. substring (packageName. length () + 3); resMap. put (className, temp) ;}} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} return resMap ;}
     
    
   
  
 

Finally, you can access all resources under the specified package through the resource ID and skinContext, for example, to access layout
/*** Get layout * in the skin package and convert it to VIEW * @ param layoutName * @ return */private View getLayoutFromSkin (String layoutName) {View view; if (resMap = null) return null; Map
 
  
Temp = resMap. get ("layout"); int viewId = (Integer) temp. get (layoutName); if (viewId! = 0) {// reference skin package resource conversion View LayoutInflater inflater = LayoutInflater. from (skinContext); view = inflater. inflate (skinContext. getResources (). getLayout (viewId), null);} else {view = null;} return view ;}
 

Note: For skin for ideas see: http://blog.csdn.net/tangnengwu/article/details/22801107


2. Access the hidden APIs of android

The closure of the Toast information box is managed by the system, because the hide method is hidden and developers cannot directly call it. In this case, you can use the launch mechanism to obtain this method, create a Toast information box that is controlled by developers.

Package com. example. reflection; import java. lang. reflect. field; import java. lang. reflect. method; import android. content. context; import android. util. log; import android. view. layoutInflater; import android. view. view; import android. widget. textView; import android. widget. toast; public class MyToast {Context context = null; Object obj = null; public MyToast (Context context, String text) {this. context = context; Toast toast = Toast. makeText (context, text, 1); try {Field field = toast. getClass (). getDeclaredField ("mTN"); field. setAccessible (true); obj = field. get (toast);} catch (Exception e) {// TODO: handle exceptionLog. d ("AAA", "MyToast Exception --->" + e. toString () ;}} public void show () {try {// android4.0 or above requires the following processing // Field mNextViewField = obj. getClass (). getDeclaredField ("mNextView"); // mNextViewField. setAccessible (true); // LayoutInflater inflate = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE); // View v = inflate. inflate (R. layout. ui_toast, null); // mNextViewField. set (obj, v); Method method = obj. getClass (). getDeclaredMethod ("show", null); method. invoke (obj, null);} catch (Exception e) {// TODO Auto-generated catch blockLog. d ("AAA", "show Exception --->" + e. toString (); e. printStackTrace () ;}} public void hide () {try {Method = obj. getClass (). getDeclaredMethod ("hide", null); method. invoke (obj, null);} catch (Exception e) {// TODO Auto-generated catch blockLog. d ("AAA", "hide Exception --->" + e. toString (); e. printStackTrace ();}}}

Display toast:
MyToast toast = new MyToast (this, "reflection mechanism! "); Toast. show ();
Hide toast:

Toast. hide ();

Note that in Versions later than 4.0, you also need to process the View in Toast, as shown in the code.


3. modify some "unchangeable" system resources

The ListView component does not provide an API for modifying the quick slider image, so it cannot be modified directly, but can be implemented through reflection.

package com.example.reflection;import java.lang.reflect.Field;import android.content.Context;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.widget.AbsListView;import android.widget.ListView;public class MListView extends ListView {public MListView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stubsetNewDrawable(context);}private void setNewDrawable(Context context){try {Field  field = AbsListView.class.getDeclaredField("mFastScroller");field.setAccessible(true);Object obj = field.get(this);field =field.getType().getDeclaredField("mThumbDrawable");field.setAccessible(true);Drawable drawable = (Drawable)field.get(obj);drawable = context.getResources().getDrawable(R.drawable.ic_launcher);field.set(obj, drawable);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
Field  field = AbsListView.class.getDeclaredField("mFastScroller");
The FastScroller. mThunbDrawable variable saves the quick slider image. However, you must first obtain the AbsListView. mFastScroller variable.


     
 


android:fastScrollEnabled="true"
Use the slider

As follows:



Summary:

The Reflection mechanism in Java is called Reflection. It allows the running Java program to check itself and directly manipulate the internal attributes or methods of the program. The Reflection mechanism allows a program to use Reflection APIs to obtain internal information of any class with a known name during execution, including: package, type parameters, superclass, implemented interfaces, inner classes, outer classes, fields, constructZ keys? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> keys/ydLUwPvTw7e0yeS7 + keys/keys + CjwvcD4KPHA + PGJyPgo8L3A + keys/ dXiuPa21M/zo6y + zb/release/M8YnI + Ci8vzai5/release + CjxwPrX308M8L3A + CjxwcmUgY2xhc3M9 "brush: java; "> method. invoke (obj, null)Use this method

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.