How do I change the value of a local variable inside an inner class?

I just found out that I can't use a non-final local variable inside an anonymous inner class, so is there any tricky way when we need to change values ​​inside inner classes without declaring instant variables?

+3


source to share


3 answers


You cannot use them for a good reason, which you need to consider before proceeding. What exactly will you do with an instance of an anonymous class? If it is only consumed locally, within this method, you can use this simple trick (let's say you have a int

var):

final int localVar[] = {1};
new AnonymousClass() {
  public void method() { localVar[0]++; }
};

      



If the instance is available after the method that created it returns, you might run into thread safety issues. The instance can be passed to other threads and the simple design above is not thread safe.

+4


source


You can write your own very simple one Holder

.

/**
 * Make a final one of these to hold non-final things in.
 */
public class Holder <T> {
  private T held = null;

  public Holder () {
  }

  public Holder (T it) {
    held = it;
  }

  public void hold(T it) {
    held = it;
  }

  public T held() {
    return held;
  }

  @Override
  public String toString () {
    return String.valueOf(held);
  }
}

      



Please don't use atoms - they have significant overhead.

final Holder<Integer> number = new Holder(0);
... {
    number.hold(n);
}
...
return number.held();

      

+2


source


You can use this snippet.

void someMethod(){
    final AtomicReference<String> var = new AtomicReference<String>("Blah")
    foo(new Bar(){
        void baz(){
             var.set("Blah-blah");
        } 
    });
}

      

0


source







All Articles