In computer science, reflection refers to a class of applications that are self-describing and self-controlling. In other words, this kind of application uses some mechanism to realize the description (self-representation) and monitoring (examination) of its own behavior, and can adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior. Reflection is Java One of the characteristics of the programming language, which allows the running Java program to check itself, or "self-audit", and can directly manipulate the internal properties of the program. The implementation of the reflection mechanism in Java is based on 4 classes: Class,constructor,field,method, which class represents the time class object, the constructor object of the Constructor-class, the Property object of the Field-class, The method object for the Method-class.
1. Through the reflection technology can access to other package name data methods, these for some apk for skin to provide a convenient
First initialize the 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 (); }
The resource ID under the specified package name can be accessed in the following way
/** * The ID of all resources for the corresponding package exists in MAP * @param packagename * @return */Private map<string,map< String, object>> Getskinresourcesid (string packagename) {map<string, object> temp = null; Map<string,map<string, object>> resmap =new hashmap<string,map<string,object>> (); try {//Get the R file in the skin pack class<?> Rclass = Skincontext.getclassloader (). LoadClass (Packag Ename+ ". R "); Gets the class class<?>[] Resclass =rclass.getclasses () that records the IDs of various resources; String Classname,resourcename; int resourceid=0; for (int i=0;i<resclass.length;i++) {className = Resclass[i].getname (); Get resources for this class Field field[] = Resclass[i].getfields (); for (Int J =0;j < Field.length; J + +) { ResourceName = Field[j].getname (); try {resourceId = Field[j].getint (resourcename); } catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace (); } catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace (); } if (Resourcename!=null &&!resourcename.equals ("")) { Temp =new hashmap<string, object> (); Temp.put (resourcename, resourceId); LOG.I ("ddddd", "ClassName:" +classname+ "resourcename:" +resourcename+ "" + "resource Id: "+integer.tohexstring (resourceId)); } }//Due to the relationship of the inner class classname should be the form of com.skin.r$layout//truncate the front package name and. R $ for ease of Use ClassName = Classname.substring (Packagename.length () +3); Resmap.put (ClassName, temp); }} catch (ClassNotFoundException e) {//TODO auto-generated catch block E . Printstacktrace (); } return resmap; }
Finally, all resources under the specified package can be accessed through the resource ID and Skincontext, for example, to access the layout
/** * Get layout in Skin pack * and convert to View * @param layoutname * @return * */ private View Getlayoutfromskin (String layoutname) { view view; if (Resmap = = null) return null; map<string, Object> temp = resmap.get ("layout"); int viewId = (Integer) temp.get (layoutname); if (viewId! = 0) { //reference Skin Pack Resource Conversion View Layoutinflater inflater =layoutinflater.from (skincontext); View = Inflater.inflate (Skincontext.getresources (). GetLayout (VIEWID), null); } else { view = null; } return view; }
Note: Change skin idea See: http://blog.csdn.net/tangnengwu/article/details/22801107
2. Access the Android hidden API
The closure of the Toast information box is managed by the system, because the Hide method is a hidden developer who has no way to invoke it directly, in which case it can be obtained using the launch mechanism to create a toast information box that shows and hides both developer-controlled.
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 ;p ublic 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 () {//android4.0 above requires the following processing//field Mnextviewfield = Obj.getclass (). Getdeclaredfield ("Mnextview ");//Mnextviewfield.setaccessible (TRUE);//layoutinflater inflate = (layoutinflater) context.getsystemservice (Conte Xt. Layout_inflater_service);//View v = inflate.inflate (r.layout.ui_toast, NULL);//MnexTviewfield.set (obj, v); 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 ();}}}
Show Toast:
Mytoast toast = new Mytoast (this, "reflection mechanism!"); Toast.show ();
Hide Toast:
Toast.hide ();
Note In more than 4.0 versions, the view in the toast also needs to be processed, as shown in the code
3. Modify some "non-modifiable" system resources
The ListView component does not provide an API to modify the speed slider image, so it cannot be modified directly, but can be implemented by 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);D rawable drawable = (drawable) field.get (obj);d rawable = 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 holds the Fast slider image, but first you get the Abslistview.mfastscroller variable
<com.example.reflection.mlistview android:id= "@+id/listview1" android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:fastscrollenabled= "true" android:scrollbars= "None" > </com.example.reflection.MListView>
Android:fastscrollenabled= "true"
Using the Fast speed slider
As follows:
Summarize:
The reflection mechanism in Java, known as reflection, allows a running Java program to examine itself and to manipulate the internal properties or methods of the program directly. The reflection mechanism allows the program to use reflection APIs to obtain internal information for any class of known name, including: package, type parameters, superclass, implemented, in the course of execution. interfaces, inner classes, outer classes, fields, constructors, methods, modifiers, etc., and can be dynamically generated during the execution of instances, Change the contents of fields or evoke methods. Again, we can use the reflection mechanism in the Java program, dynamic to call some protected or even private methods or classes, which can greatly satisfy some of our more special needs.
API for Reflection Technology:
Class:
Class classes represent a class of bytecode, to use reflection, you need to get the corresponding class object, and then through this object, you can dissect the class member variables, member methods and so on.
Get Class object
This method is most commonly used with class Class1 = Class.forName (ClassName) through the forname () method of class. Through the. Class class Class2 = Xxx.class; Get Class CLASS3 = new XXX () by object. GetClass ();
Common methods of class:
GetConstructor () Gets the constructor GetMethod () Gets the member method GetField () Gets the member variable Getdeclaredconstructor () Gets the private constructor Getdeclaredmethod () Gets the private member Method Getdeclaredfield () Gets the private member variable
After acquiring the method object
Call
Method.invoke (obj, null)
Use this method