在Java中访问私有变量

时间:2014-03-23 06:59:44

标签: java private access-control

我想从下面的代码中访问实例变量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 ); 
    }
}

3 个答案:

答案 0 :(得分:2)

getter 方法添加到Controller类中:

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

编辑:然后在其他课程中访问它(在初始化Controller之后)。

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

答案 1 :(得分:1)

在其他类的实例上访问不可访问的字段通常是一个坏主意,但在某些情况下,这是获得某些功能的唯一方法。

我的建议:首先检查是否没有其他方法可以达到你想要的效果。

然而,在某些情况下,没有别的办法。例如,您使用的第三方库由于某种原因不允许您修改,并且您需要访问其中未以任何其他方式公开的字段。

如果你真的需要这样做,我会在代码周围发出很多重要的警告意见,以便那些必须维护代码的人至少知道发生了什么不好的事情,以及你的推理是什么因为它是。


也就是说,有一种方法可以使用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);
    }
}

您可以将此方法放在代码中的任何位置,这样您就可以阅读totalTime子类实例的Controller字段。

答案 2 :(得分:0)

首先,添加getter&amp;类控制器中的setter .. 然后使用BloodBankAgent然后使用S2842663BloodBankAget继承多级别的类。

相关问题