一類的私有對象的方法,我有下面的類:調用Android中/ JAVA
public class Foo {
private View myButton;
...
}
我想打電話foo.myButton.performClick()。但我不能修改Foo類,因爲它是一個庫。我該怎麼做?
我與
Field mField= Foo.class.getDeclaredField("myButton");
努力,但我不知道如何從現場獲得的觀看基準
感謝
一類的私有對象的方法,我有下面的類:調用Android中/ JAVA
public class Foo {
private View myButton;
...
}
我想打電話foo.myButton.performClick()。但我不能修改Foo類,因爲它是一個庫。我該怎麼做?
我與
Field mField= Foo.class.getDeclaredField("myButton");
努力,但我不知道如何從現場獲得的觀看基準
感謝
隨着
Field mField = Foo.class.getDeclaredField("myButton")
你會獲得該領域的規範的參考。數據包括有訪問器,它擁有的價值等的類型。如果你想獲得的視圖的參考,你需要做到以下幾點:
View viewReference = (View)mField.get(fooInstance);
訪問私有字段(像反射你需要確保該字段是可訪問的:
mField.setAccessible(true);
我會建議恢復國旗,一旦你得到的參考。根據你所面臨的情況,可能會有更好的解決方案。
好運
沒有辦法使用/得到私人領域或方法。這是java規則。你不能繼承私人領域/方法。私有方法/字段在它們定義的類中受到限制。
爲了獲得私人信息,必須有更好的答案。該信息幾乎肯定是私人的有一個原因。
但是,你可以做到這一點,利用get
像這樣(代碼中獲得mField
後):
mField.setAccessible(true);
View button = (View)mField.get(theFooInstance);
(您需要setAccessible
調用,因爲默認情況下,私有字段無法訪問。)
您可能需要在實際獲取該字段之前將該字段設置爲true:
Field field = Foo.getClass().getDeclaredField("myButton"));
field.setAccessible(true);
View button = (View) field.get(fooInstance);
我想你可以嘗試通過java反射來完成它。類似於:
Foo obj = new Foo();
Method method = obj.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object result = method.invoke(obj);
實際上,您可以用反射。你***不應該***,但你可以。 –
閱讀有關反思:http://docs.oracle.com/javase/tutorial/reflect/ –