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

前端 未结 20 2217
一向
一向 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:39

    One solution I have noticed isn't mentioned (unless I missed it, if I did please correct me), is the use of a class variable. Ran into this issue attempting to run a new thread within a method: new Thread(){ Do Something }.

    Calling doSomething() from the following will work. You do not necessarily have to declare it final, just need to change the scope of the variable so it is not collected before the innerclass. This is unless of course your process is huge and changing the scope might create some sort of conflict. I didn't want to make my variable final as it was in no way a final/constant.

    public class Test
    {
    
        protected String var1;
        protected String var2;
    
        public void doSomething()
        {
            new Thread()
            {
                public void run()
                {
                    System.out.println("In Thread variable 1: " + var1);
                    System.out.println("In Thread variable 2: " + var2);
                }
            }.start();
        }
    
    }
    

提交回复
热议问题