简体   繁体   English

在Java中访问私有变量

[英]Accessing a private variable in Java

I would like to access the instance variable total time from the code below: 我想从下面的代码访问实例变量total time

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

in the code below 在下面的代码中

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 ); 
    }
}

Add a getter method to the Controller class as: 将一个getter方法添加到Controller类中:

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

EDIT: Then access it in the other class (after you initialize a Controller ). 编辑:然后在其他类中访问它(初始化Controller )。

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

Accessing non-accessible fields on instances of other classes is generally a bad idea, but there are situations in which it is the only way to get something to work. 访问其他类的实例上的不可访问字段通常是一个坏主意,但在某些情况下,它是获得某些功能的唯一方法。

My advice: first check if there is no other way to achieve what you want. 我的建议:首先检查是否没有其他方法可以达到你想要的效果。

However there are situations in which there is no other way. 然而,在某些情况下,没有其他办法。 For example, you're using a third-party library, which you're not allowed to modify for some reason, and you need to access a field in it that it has not exposed in any other way. 例如,您正在使用第三方库,由于某种原因您不允许修改它,并且您需要访问其中未以任何其他方式公开的字段。

I would put a lot of big warning comments around the code, if you really need to do it, so that the people who have to maintain the code after you at least know that something bad is going on, and what your reasoning for it was. 如果你真的需要这样做的话,我会在代码周围发出很多重要的警告意见,以便那些必须在你至少知道坏事发生之后维护代码的人,以及你的理由是什么。


That said, there is a way using the Reflection API to access non-accessible fields. 也就是说,有一种方法可以使用Reflection API来访问不可访问的字段。 It doesn't always work: if a SecurityManager has been installed, your attempt will be rejected. 它并不总是有效:如果安装了SecurityManager ,您的尝试将被拒绝。 So it won't work in JavaWebStart applications or Applets, for example, or on an application server with a SecurityManager. 因此,它不能在JavaWebStart应用程序或Applet中工作,或者在具有SecurityManager的应用程序服务器上工作。 But in most cases, it does actually work. 但在大多数情况下,它确实有效。

Code to read an otherwise inaccessible int field: 用于读取其他无法访问的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);
    }
}

You can put this method anywhere in your code and it will allow you to read the totalTime field of an instance of a subclass of Controller . 您可以将此方法放在代码中的任何位置,它将允许您读取Controller子类实例的totalTime字段。

首先,在类Controller中添加getter和setter。然后使用BloodBankAgent然后使用S2842663BloodBankAget在多级中继承该类。

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

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