Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a reasonable way to mutate a primitive variable from an anonymous Java class?

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?

like image 213
Steve Avatar asked Jan 23 '23 03:01

Steve


1 Answers

I tend to do the boolean[1] method you mentioned:

final boolean[] found = {false};
search(new SearchCallback() {
  @Override void onFound(Object o) { found[0] = true; }
});

It's a bit hackish, but it tends to be the closest thing to what you actually want

like image 102
Michael Mrozek Avatar answered Feb 08 '23 10:02

Michael Mrozek