简体   繁体   中英

Accessing a private variable in Java

I would like to access the instance variable total time from the code below:

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:

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

EDIT: Then access it in the other class (after you initialize a 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. It doesn't always work: if a SecurityManager has been installed, your attempt will be rejected. So it won't work in JavaWebStart applications or Applets, for example, or on an application server with a SecurityManager. But in most cases, it does actually work.

Code to read an otherwise inaccessible int field:

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中添加getter和setter。然后使用BloodBankAgent然后使用S2842663BloodBankAget在多级中继承该类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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