簡體   English   中英

在Java中訪問私有變量

[英]Accessing a private variable in Java

我想從下面的代碼訪問實例變量total time

public abstract class Controller{
    protected int currentTime; 
    protected int totalTime; 
    protected Agent[][][] player; 

在下面的代碼中

public class S2842663BloodBankAgent extends BloodBankAgent {

    private BoardComponentList knownBloodBanks; 
    private BoardComponentList knownDonor; 

    public S2842663BloodBankAgent(){
        super(); 
        knownBloodBanks = new BoardComponentList(); 
        knownDonor = new BoardComponentList();
    }

    public S2842663BloodBankAgent( BoardComponent bC ) {
        super( bC ); 
    }
}

將一個getter方法添加到Controller類中:

...
public int getTotalTime() {
    return totalTime;
}
...

編輯:然后在其他類中訪問它(初始化Controller )。

...
Controller controller = new Controller();
//...do necessary things.
int time = controller.getTotalTime();
...

訪問其他類的實例上的不可訪問字段通常是一個壞主意,但在某些情況下,它是獲得某些功能的唯一方法。

我的建議:首先檢查是否沒有其他方法可以達到你想要的效果。

然而,在某些情況下,沒有其他辦法。 例如,您正在使用第三方庫,由於某種原因您不允許修改它,並且您需要訪問其中未以任何其他方式公開的字段。

如果你真的需要這樣做的話,我會在代碼周圍發出很多重要的警告意見,以便那些必須在你至少知道壞事發生之后維護代碼的人,以及你的理由是什么。


也就是說,有一種方法可以使用Reflection API來訪問不可訪問的字段。 它並不總是有效:如果安裝了SecurityManager ,您的嘗試將被拒絕。 因此,它不能在JavaWebStart應用程序或Applet中工作,或者在具有SecurityManager的應用程序服務器上工作。 但在大多數情況下,它確實有效。

用於讀取其他無法訪問的int字段的代碼:

import java.lang.reflect.Field;

// [...]

public static int accessTotalTime(Controller c) {
    try {
        Field totalTime = Controller.class.getDeclaredField("totalTime");
        totalTime.setAccessible(true); // <-- Necessary for inaccessible fields
        return totalTime.getInt(c);
    } catch (IllegalAccessException | NoSuchFieldException e) {
        throw new Error(e);
    }
}

您可以將此方法放在代碼中的任何位置,它將允許您讀取Controller子類實例的totalTime字段。

首先,在類Controller中添加getter和setter。然后使用BloodBankAgent然后使用S2842663BloodBankAget在多級中繼承該類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM