简体   繁体   中英

Java: “Cannot refer to a non-final variable inside an inner class […]”, difference between OS X and Windows

I've got some code from a project developed in Eclipse on OS X. The problem is that I get error messages that appear when the code is run on Windows, but not when it is run on OS X.

The following is done in the main function of a program.

Mainbus mainbus = new Mainbus();    

    (new Thread(new Runnable(){
        @Override
        public void run(){
            MatlabProxyConnection matlabproxy = new MatlabProxyConnection();
            mainbus.setMatlabProxyConnection(matlabproxy);
            matlabproxy.startMatlab("quiet");
        }
    })).start();

When I try to run the code on Windows I get an error message:

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

It seems that Eclipse on Windows is more strict; that it actually is an error in the code that has to be fixed. What is the best solution to make it work on both systems? Is the best solution to change the declaration of mainbus to final, or should I define a new class implementing Thread, so I can pass mainbus in the constructor?

刚刚设置mainbus final

final Mainbus mainbus = new Mainbus();  
final Mainbus mainbus = ...;

The final restriction was later relaxed to the local variable being not assigned to, that is the variable could have been made final. So make it final.

The main reason being, that in runnable there actually is used a new variable mainbus as the two variables (memory address where the object pointer is stored) have different life times.

The relaxation was needed for (nested) lambda usage, parameters.

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