1. 程式人生 > >在外部類呼叫一個類的private 變數

在外部類呼叫一個類的private 變數

通過Java 反射技術來讀寫 private 變數,以AnimaionDrawable 類中的mCurFrame變數為例,該變數是int 型別,儲存當前動畫的播放位置, 程式碼如下:
// 獲得mCurFrame 變數的 Field 物件
java.lang.reflect.Field field = AnimationDrawable.getDeclareField("mCurFrame");
// 將mCurFrame 變數設定為可訪問狀態
field.setAccessible(true);
// 獲得mCurFrame 變數當前的值
int curFrame = field.getInt(animationDrawable);
// 設定mCurFrame 變數的值
field.setInt(animationDrawable, -1);

強調一點: 雖然可以使用getDeclareField() 獲得mCurFrame 變數的 field 物件,但 是mCurFrame 是private 變數,預設情況下無法直接通過field 獲得和設定mCurFrame變數的值,因此需要通過setAccessible () 將field 設定成可訪問狀態.