Modifying an outer variable within an anonymous inner class

家住魔仙堡 提交于 2019-12-11 21:50:48

问题


As I understand it, any variables used within an inner anonymous class (but declared outside of it) are actually passed a copy of their values. There is also a requirement that these outer variables be declared as final, which obviously means that these variables are not meant to be modified.

But is there any kind of work-around to this? Can my anonymous inner class actually modify some variable or object, which I could then use later on in my code (outside of the anonymous class)? Or would the modifications not be seen outside of the anonymous class?


回答1:


The behavior you are referring to applies only to local variables or method/catch parameters. You can access and, potentially, modify instance members just fine

public class Example {

    public void method() {
        String localFoo = "local";
        new Object() {
            public void bar() {
                foo = "bar"; // yup
                System.out.println(localFoo); // sure
                localFoo = "bar"; // nope
            }
        };        
    }

    private String foo = "foo";
}

The anonymous Object inner class copies the value of localFoo for use within the println(..) invocation. However, for foo, it's actually "copying" the reference to the Example instance and referencing its foo field.

It's actually equivalent to

Example.this.foo = "bar";



回答2:


Referenced objects do indeed need to be final - however, they can be mutable.

class Holder<T> {
    public T held;
}

public void test() {
    final Holder<String> s = new Holder<>();
    new Runnable () {

        @Override
        public void run() {
            s.held = "Hello;";
        }

    }
}

This is greatly simplified - you would normally use getters and setters for the held value.



来源:https://stackoverflow.com/questions/27661649/modifying-an-outer-variable-within-an-anonymous-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!