反射加载
来源:互联网 发布:希区柯克 为什么 知乎 编辑:程序博客网 时间:2024/05/16 10:36
一个文件去访问一个文件里的private 方法或者变量,控件等;
首先看一下我这个Activity里面的代码
- public class FanSheActivity extends AppCompatActivity {
-
- private TextView mName;
- private TextView mAddress;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fan_she);
- mName = (TextView) findViewById(R.id.id_name);
- mAddress = (TextView) findViewById(R.id.id_address);
-
- getNameText();
- showgetProsenaddress();
- }
-
-
-
-
- public void getNameText() {
- Field f;
- String name = null;
- FanShePresenter mFanShePresenter = new FanShePresenter(this);
- Class temp = mFanShePresenter.getClass();
- try {
- f = temp.getDeclaredField("name");
- f.setAccessible(true);
- name = (String) f.get(mFanShePresenter);
- } catch (Exception e) {
- e.printStackTrace();
- }
- mName.setText(name);
- }
-
-
-
-
- public void showgetProsenaddress() {
- Method method = null;
- FanShePresenter mFanShePresenter = new FanShePresenter(this);
- Class temp = mFanShePresenter.getClass();
- try {
- method = temp.getDeclaredMethod("getProsenaddress", null);
- method.setAccessible(true);
- method.invoke(mFanShePresenter, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
下面是要访问的类文件-
-
-
- public class FanShePresenter {
-
- private String name;
- public String address;
- public Context mContext;
-
- public FanShePresenter(Context mContext) {
- this.name = "奥巴马";
- this.address = "美国五角大楼";
- this.mContext = mContext;
- }
-
- public void getProsenName() {
- Toast.makeText(mContext, "习大大", Toast.LENGTH_LONG).show();
- }
-
- private void getProsenaddress() {
- Toast.makeText(mContext, "北京天安门", Toast.LENGTH_LONG).show();
- }
- }
0 0