How to change value of a local variable inside an inner class?

android, inner-classes, java

Solution

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

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

If the instance will be reachable after the method which created it returns, then you may get thread-safety issues. The instance may be passed to other threads and the simple design above is not thread-safe.

Problem

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

Original source