java - 无法引用在不同方法中定义的内部类内的非最终变量

标签 java methods declaration final

编辑: 我需要更改几个变量的值,因为它们通过计时器运行多次。我需要在计时器的每次迭代中不断更新值。我无法将值设置为最终值,因为这会阻止我更新值,但是我收到了我在下面的初始问题中描述的错误:

我之前写过以下内容:

I am getting the error "cannot refer to a non-final variable inside an inner class defined in a different method".

This is happening for the double called price and the Price called priceObject. Do you know why I get this problem. I do not understand why I need to have a final declaration. Also if you can see what it is I am trying to do, what do I have to do to get around this problem.

public static void main(String args[]) {

    int period = 2000;
    int delay = 2000;

    double lastPrice = 0;
    Price priceObject = new Price();
    double price = 0;

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            price = priceObject.getNextPrice(lastPrice);
            System.out.println();
            lastPrice = price;
        }
    }, delay, period);
}

最佳答案

Java 不支持 true closures ,即使使用像这里使用的匿名类 (new TimerTask() { ... }) 看起来像是一种闭包。

编辑 - 请参阅下面的评论 - 正如 KeeperOfTheSoul 指出的那样,以下解释不正确。

这就是它不起作用的原因:

变量lastPrice和price是main()方法中的局部变量。使用匿名类创建的对象可能会持续到 main() 方法返回之后。

main()方法返回时,局部变量(例如lastPriceprice)将从堆栈中清除,因此main() 返回后它们将不再存在。

但是匿名类对象引用了这些变量。如果匿名类对象在变量被清理后尝试访问它们,事情就会变得非常错误。

通过设置lastPricepricefinal,它们不再是真正的变量,而是常量。然后,编译器可以将匿名类中 lastPriceprice 的使用替换为常量的值(当然是在编译时),并且您不会不再有访问不存在的变量的问题。

其他支持闭包的编程语言是通过特殊处理这些变量来实现的 - 确保它们在方法结束时不会被销毁,以便闭包仍然可以访问变量。

@Ankur:你可以这样做:

public static void main(String args[]) {
    int period = 2000;
    int delay = 2000;

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        // Variables as member variables instead of local variables in main()
        private double lastPrice = 0;
        private Price priceObject = new Price();
        private double price = 0;

        public void run() {
            price = priceObject.getNextPrice(lastPrice);
            System.out.println();
            lastPrice = price;
        }
    }, delay, period);      
}

关于java - 无法引用在不同方法中定义的内部类内的非最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26364458/

相关文章:

Java Swing "children"窗口

java - Primefaces,如何用另一个按钮折叠布局单元?

c++ - 在 C++ 中表示时间

c - C 中声明的、未初始化的变量会发生什么?它有值(value)吗?

java - 我想在 Spring 项目中使用 JSP 文件的开发版本。是否可以?

java - 为什么你可以抛出一个未发生的异常但不捕获它

javascript - 获取方法外部的变量(对象)

c# - 通过方法调用将自定义对象传递给 DLL

c++ - 为什么它是指向 void 声明符的指针而不是指向成员函数的指针?

c 字符串基础知识,为什么未分配?