android中使用反射机制,调用framework中的方法。有的时候重写类的话太麻烦,也有很多资源需要添加,因此,使用反射机制调用系统的方法会比较简单一些。
首先写一个单独的类,ReflectionInternal.java,用以获得这个类,和需要用到的方法。
1 public class ReflectionInternal { 2 Object obj; 3 Class sm; 4 public ReflectionInternal(Context context,String str){ 5 try { 6 sm = Class.forName(str); 7 8 } catch (ClassNotFoundException e1) { 9 e1.printStackTrace(); 10 } 11 } 12 public Object getInstence(Context context,KeyboardView mKeyboardView, View mPasswordEntry){ 13 if(sm != null){ 14 try { 15 Constructor c = sm.getConstructor(Context.class,KeyboardView.class,View.class); 16 if(c != null){ 17 try { 18 obj = c.newInstance(context,mKeyboardView,mPasswordEntry); 19 } catch (IllegalArgumentException e) { 20 // TODO Auto-generated catch block 21 e.printStackTrace(); 22 } catch (InstantiationException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } catch (IllegalAccessException e) { 26 // TODO Auto-generated catch block 27 e.printStackTrace(); 28 } catch (InvocationTargetException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 } 33 } catch (SecurityException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 } catch (NoSuchMethodException e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } 40 } 41 return null; 42 } 43 public void setInt(String method,int mode){ 44 if(obj != null){ 45 try { 46 Method m = obj.getClass().getMethod(method, int.class); 47 if(m != null){ 48 try { 49 m.invoke(obj, mode); 50 } catch (IllegalArgumentException e) { 51 // TODO Auto-generated catch block 52 e.printStackTrace(); 53 } catch (IllegalAccessException e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } catch (InvocationTargetException e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 } 60 } 61 } catch (SecurityException e) { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 } catch (NoSuchMethodException e) { 65 // TODO Auto-generated catch block 66 e.printStackTrace(); 67 } 68 } 69 } 70 71 }
代码中使用的时候:
private ReflectionInternal mKeyboardHelper; private void initViews() {
//类的包名和类名,"com.android.internal.widget.PasswordEntryKeyboardHelper"
mKeyboardHelper = new ReflectionInternal(this,"com.android.internal.widget.PasswordEntryKeyboardHelper");
//调用类,声明类,mKeyboardView,mPasswordEntry,为需要传递的参数
mKeyboardHelper.getInstence(this, mKeyboardView, mPasswordEntry);
//调用方法,并传递参数 mKeyboardHelper.setInt("setKeyboardMode", 0); }
没用过的时候觉得很难,用过一次之后发现没那么难了,也很方便,特别适合单个的apk应用中使用,如果是在整个工程中是不需要这么麻烦的调用framework中的类的。