简体   繁体   English

从内部类中访问变量

[英]Variable is accessed from within inner class

I have these varibles: 我有这些变量:

private boolean MineRunning;
private BigInteger MineProfit;
etc....

I want to call the countdown method: 我想调用倒计时方法:

countdown(MineRunning, MineProfit, MineTime, MineProgressbar, MineProgressstatus);

ca. ca. 10 Times for different things 10次​​不同的事情

The method: 方法:

private void countdown(boolean running,  BigInteger profit, BigInteger time,  ProgressBar progressBar, int progressStatus) {
    if(!running && Reference.Storage_Filled.add(profit).compareTo(Reference.Storage_Capacity) == 0 ||
            !running && Reference.Storage_Filled.add(profit).compareTo(Reference.Storage_Capacity) == -1){
        running = true;

        new CountDownTimer(time.longValue(), Reference.countDownInterval.longValue()){
            public void onTick(long millisUntilFinished){
                progressStatus++;
                progressBar.setProgress(progressStatus);
            }

            public void onFinish(){

                Reference.totalGravel = Reference.totalGravel.add(profit);
                Gravelrefresh();

                progressStatus = 0;
                progressBar.setProgress(progressStatus);

                running = false;
            }
        }.start();

    }
}

If I call this method i get an error: 如果我调用此方法,则会收到错误消息:

variable is accessed from within inner class 从内部类中访问变量

I dont want to make the varibles to final because I have to edit these in the method. 我不想使变量final因为我必须在方法中进行编辑。 What can I do instead? 我该怎么办? Thanks. 谢谢。

If your inner class is performing work on a separate thread, which seems to be the case here, you cannot access variables from this inner class. 如果您的内部类在单独的线程上执行工作(在这里似乎是这种情况),则无法从该内部类访问变量。 What you can do however, you can pass these variables as parameters to your inner class constructor, create new variables, copy them and manipulate. 但是,您可以做的是,可以将这些变量作为参数传递给内部类构造函数,创建新变量,复制它们并进行操作。

Or you just declare them as final, that's not a problem most of the time. 或者您只是将它们声明为final,大多数时候这不是问题。

Any variable accessed by an inner class must either be final or be a class scoped variable. 内部类访问的任何变量必须是final或是类范围的变量。 There is no way around that. 没有办法解决。 Either don't update those variables, or follow the rules. 要么不更新这些变量,要么遵循规则。

Adding final normally isn't a problem. 通常添加final不是问题。 Final doesn't prevent you from mutating an object, it just prevents you from assigning to the reference. Final不会阻止您更改对象,而只是阻止您分配给引用。 You can still call a function like setProgress that changes its internal state. 您仍然可以调用诸如setProgress之类的函数来更改其内部状态。

What if you make those variables static 如果您将这些变量设为静态怎么办

private static boolean MineRunning;
private static BigInteger MineProfit;
...

And make your method parameter less 并减少您的方法参数

private void countdown(){ 
    //Your code here
}

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

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