Sometimes I would like to pass an immutable object to a method and change its value inside of the method or I would like the assign another object to the parameter reference (example 1). Or I would like to assign inside of an anonymous inner class another object to a final local variable (example 2). Because all of these cases are not possible, sometimes I use an Atomic(Integer|Long…) class or a list (which is really bad, because a list can contain multiple objects) for this purpose. Alternatively, I could create a class which holds an object and allows changing the object:
public class ReferenceExample {
public static void main(String[] args) {
final Reference<String> string = new Reference<>("a");
// Example 1:
method(string);
// Example 2:
new Thread() {
@Override
public void run() {
string.set("c");
};
}.start();
}
public static void method(Reference<String> string) {
string.set("b");
}
private static class Reference<T> {
private T value;
public Reference() {}
public Reference(T value) {
this.value = value;
}
public T get() {
return value;
}
public void set(T value) {
this.value = value;
}
}
}
I am wondering if such a class does already exists in Java or a common library (e.g. in an apache common project)? If not, are there any other good solutions for these problems?
You’ve found the main solution, but the other two common approaches are
AtomicReference, which it looks like you’ve already foundThat said, you can usually find ways around the need: