What's a reasonable way to mutate a primitive variable from an anonymous Java class?
- by Steve
I would like to write the following code:
boolean found = false;
search(new SearchCallback() {
@Override void onFound(Object o) { found = true; }
});
Obviously this is not allowed, since found needs to be final. I can't make found a member field for thread-safety reasons. What is the best alternative? One workaround is to define
final class MutableReference<T> {
private T value;
MutableReference(T value) { this.value = value; }
T get() { return value; }
void set(T value) { this.value = value; }
}
but this ends up taking a lot of space when formatted properly, and I'd rather not reinvent the wheel if at all possible. I could use a List<Boolean> with a single element (either mutating that element, or else emptying the list) or even a Boolean[1]. But everything seems to smell funny, since none of the options are being used as they were intended.
What is a reasonable way to do this?