I am currently reading here that in order to achieve immutability of my object, I have to:
- Declare all my fields private and final
- Not define setters
Why do I need to declare the fields final if there are no setters anyways. The java compiler doesn't allow something like this:
myObj.getSomething() = new Somthing()
If I try to use reflection, then the final
keyword doesn't stop me from changing the reference.
I found a very nice explanation here why the entire class needs to be final
but nothing about why the private fields need to be final.
Edit: As a reply to GotoFinal's comment Here is a class that shows how I can edit the field with reflection:
public class Test {
static class Immutable {
private final StringBuilder immutableField = new StringBuilder("You can't set final field just by normal reflections");
public StringBuilder getStringBuilder() {
return immutableField;
}
}
public static void main(String[] args) throws Exception {
Immutable immutableObject = new Immutable();
Field f1 = immutableObject.getClass().getDeclaredField("immutableField");
f1.setAccessible(true);
f1.set(immutableObject, new StringBuilder("Well, I just did"));
System.out.println(immutableObject.getStringBuilder());
}
}