简体   繁体   中英

Modify local variable from anonymous inner class

I found that we can't modify local variables from inner class as it's defined as final. While reading I found that we have to mark it as final so it does not create any value mismatch issue. But what if we really want to modify the local variable from inner class. Is there any work around?

You can't modify the local variable. But if the local variable is an object reference, you can modify the object it refers to. For example:

public static void main(String[] args) {
    final AtomicReference<String> value = new AtomicReference<String>("hello");

    System.out.println(value); // prints "hello"

    new Runnable() {
        public void run() { value.set("goodbye"); }
    }.run();

    System.out.println(value); // prints "goodbye"
}

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