How do I change the value of a local variable inside an inner class?
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 to share
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 to share