Cannot refer to a non-final variable inside an inner class defined in a different method

前端 未结 20 2216
一向
一向 2020-11-21 05:04

Edited: I need to change the values of several variables as they run several times thorugh a timer. I need to keep updating the values with every iteration through the timer

20条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 05:45

    When I stumble upon this issue, I just pass the objects to the inner class through the constructor. If I need to pass primitives or immutable objects (as in this case), a wrapper class is needed.

    Edit: Actually, I don't use an anonymous class at all, but a proper subclass:

    public class PriceData {
            private double lastPrice = 0;
            private double price = 0;
    
            public void setlastPrice(double lastPrice) {
                this.lastPrice = lastPrice;
            }
    
            public double getLastPrice() {
                return lastPrice;
            }
    
            public void setPrice(double price) {
                this.price = price;
            }
    
            public double getPrice() {
                return price;
            }
        }
    
        public class PriceTimerTask extends TimerTask {
            private PriceData priceData;
            private Price priceObject;
    
            public PriceTimerTask(PriceData priceData, Price priceObject) {
                this.priceData = priceData;
                this.priceObject = priceObject;
            }
    
            public void run() {
                priceData.setPrice(priceObject.getNextPrice(lastPrice));
                System.out.println();
                priceData.setLastPrice(priceData.getPrice());
    
            }
        }
    
        public static void main(String args[]) {
    
            int period = 2000;
            int delay = 2000;
    
            PriceData priceData = new PriceData();
            Price priceObject = new Price();
    
            Timer timer = new Timer();
    
            timer.scheduleAtFixedRate(new PriceTimerTask(priceData, priceObject), delay, period);
        }
    

提交回复
热议问题