反射加载

来源:互联网 发布:希区柯克 为什么 知乎 编辑:程序博客网 时间:2024/05/16 10:36

一个文件去访问一个文件里的private 方法或者变量,控件等;


首先看一下我这个Activity里面的代码

[java] view plain copy
  1. public class FanSheActivity extends AppCompatActivity {  
  2.   
  3.     private TextView mName;  
  4.     private TextView mAddress;  
  5.   
  6.     @Override  
  7.     protected void onCreate(Bundle savedInstanceState) {  
  8.         super.onCreate(savedInstanceState);  
  9.         setContentView(R.layout.activity_fan_she);  
  10.         mName = (TextView) findViewById(R.id.id_name);  
  11.         mAddress = (TextView) findViewById(R.id.id_address);  
  12.         /**下面我们通过发射来拿到FanShePresenter里面的private修饰变量和方法*/  
  13.         getNameText();  
  14.         showgetProsenaddress();  
  15.     }  
  16.   
  17.     /** 
  18.      * 我们首先来拿到private修饰的字段name 
  19.      */  
  20.     public void getNameText() {  
  21.         Field f;  
  22.         String name = null;  
  23.         FanShePresenter mFanShePresenter = new FanShePresenter(this);  
  24.         Class temp = mFanShePresenter.getClass();  
  25.         try {  
  26.             f = temp.getDeclaredField("name");  
  27.             f.setAccessible(true);  
  28.             name = (String) f.get(mFanShePresenter);  
  29.         } catch (Exception e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.         mName.setText(name);  
  33.     }  
  34.   
  35.     /** 
  36.      * 调用private修饰的方法getProsenaddress() 
  37.      */  
  38.     public void showgetProsenaddress() {  
  39.         Method method = null;  
  40.         FanShePresenter mFanShePresenter = new FanShePresenter(this);  
  41.         Class temp = mFanShePresenter.getClass();  
  42.         try {  
  43.             method = temp.getDeclaredMethod("getProsenaddress"null);  
  44.             method.setAccessible(true);  
  45.             method.invoke(mFanShePresenter, null);  
  46.         } catch (Exception e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.     }  
  50. }  

下面是要访问的类文件

[java] view plain copy
  1. /** 
  2.  *  
  3.  */  
  4. public class FanShePresenter {  
  5.   
  6.     private String name;  
  7.     public String address;  
  8.     public Context mContext;  
  9.   
  10.     public FanShePresenter(Context mContext) {  
  11.         this.name = "奥巴马";  
  12.         this.address = "美国五角大楼";  
  13.         this.mContext = mContext;  
  14.     }  
  15.   
  16.     public void getProsenName() {  
  17.         Toast.makeText(mContext, "习大大", Toast.LENGTH_LONG).show();  
  18.     }  
  19.   
  20.     private void getProsenaddress() {  
  21.         Toast.makeText(mContext, "北京天安门", Toast.LENGTH_LONG).show();  
  22.     }  
  23. }  
0 0
原创粉丝点击