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

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

    I just wrote something to handle something along the authors intention. I found the best thing to do was to let the constructor take all the objects and then in your implemented method use that constructor objects.

    However, if you are writing a generic interface class, then you have to pass an Object, or better a list of Objects. This could be done by Object[] or even better, Object ... because it is easier to call.

    See my example piece just below.

    List lst = new ArrayList();
    lst.add("1");
    lst.add("2");        
    
    SomeAbstractClass p = new SomeAbstractClass (lst, "another parameter", 20, true) {            
    
        public void perform( ) {                           
            ArrayList lst = (ArrayList)getArgs()[0];                        
        }
    
    };
    
    public abstract class SomeAbstractClass{    
        private Object[] args;
    
        public SomeAbstractClass(Object ... args) {
            this.args = args;           
        }      
    
        public abstract void perform();        
    
        public Object[] getArgs() {
            return args;
        }
    
    }
    

    Please see this post about Java closures that supports this out of the box: http://mseifed.blogspot.se/2012/09/closure-implementation-for-java-5-6-and.html

    Version 1 supports passing of non-final closures with autocasting:
    https://github.com/MSeifeddo/Closure-implementation-for-Java-5-6-and-7/blob/master/org/mo/closure/v1/Closure.java

        SortedSet sortedNames = new TreeSet();
        // NOTE! Instead of enforcing final, we pass it through the constructor
        eachLine(randomFile0, new V1(sortedNames) {
            public void call(String line) {
                SortedSet sortedNames = castFirst();  // Read contructor arg zero, and auto cast it
                sortedNames.add(extractName(line));
            }
        });
    

提交回复
热议问题