简体   繁体   English

在Android / java中调用类的私有对象的方法

[英]Call a method of a private object of a class in Android/java

I have the following class: 我有以下课程:

public class Foo {
    private View myButton;
    ...
}

I'd like to call foo.myButton.performClick(). 我想调用foo.myButton.performClick()。 But I can't modify the Foo class since it is a library. 但是我无法修改Foo类,因为它是一个库。 How can I do it? 我该怎么做?

I'm trying with 我正在尝试

Field mField= Foo.class.getDeclaredField("myButton");

but I don't know how to get the View reference from the Field 但我不知道如何从现场获取“视图”参考

Thanks 谢谢

With

Field mField = Foo.class.getDeclaredField("myButton")

you will get the reference of the specification of the field. 您将获得该领域规范的参考。 Data included there is the accessors, the type of the value it holds, etc.. If you want to get the reference of the view you need to do the following: 其中包含的数据包括访问器,它包含的值的类型等。如果要获取视图的引用,则需要执行以下操作:

View viewReference = (View)mField.get(fooInstance);

To access private fields (with reflection like mentioned below), you need to make sure the field is accessible: 要访问私有字段(具有如下所述的反射),您需要确保该字段可访问:

mField.setAccessible(true);

I would recommend to restore the flag once you got the reference. 一旦您获得参考,我建议还原该标志。 Depending on the scenario you are facing, probably there is a better solution. 根据您所面对的场景,可能有更好的解决方案。

Good Luck 祝好运

There's no way to use/get private fields or methods. 无法使用/获取私有字段或方法。 That's java rule. 那是java规则。 You can't inherit a private field/method. 您不能继承私有字段/方法。 Private methods/fields are restricted within the class they are defined. 专用方法/字段被限制在它们定义的类内。

There must be a better answer than breaking into the instance to get at its private information. 必须有比进入实例获取其私有信息更好的答案。 The information is almost certainly private for a reason . 由于某种原因,该信息几乎肯定是私有

However, you can do it, using get like this (after your code getting mField ): 但是,您可以使用get 做到这一点(在代码获取mField ):

mField.setAccessible(true);
View button = (View)mField.get(theFooInstance);

(You need the setAccessible call because by default private fields are not accessible.) (您需要setAccessible调用,因为默认情况下私有字段不可访问。)

You may need to set the accesible to true on that field before actually getting it: 您可能需要在实际获取该字段之前将accesible设置为true:

Field field = Foo.getClass().getDeclaredField("myButton"));
      field.setAccessible(true);
View button = (View) field.get(fooInstance);

i think you could try to do it via java reflection. 我认为您可以尝试通过Java反射来做到这一点。 smth similar to: 类似于:

Foo obj = new Foo();

Method method = obj.getClass().getDeclaredMethod( methodName );
method.setAccessible(true);

Object result = method.invoke(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM