I want to design a class to demonstrate immutability, incrementally.
Following is a simple class
public class ImmutableWithoutMutator {
private final String firstName;
private final String lastName;
private final int age;
public ImmutableWithoutMutator(final String firstName, final String lastName, final int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Override
public String toString() {
return String.format(
"ImmutableWithoutMutator [age=%s, firstName=%s, lastName=%s]",
age, firstName, lastName);
}
}
Now I can still breach in using reflection, by using the following code.
import java.lang.reflect.Field;
public class BreakImmutableUsingReflection {
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
ImmutableWithoutMutator immMutator = new ImmutableWithoutMutator(
"firstName", "lastName", 2400);
System.out.println(immMutator);
// now lets try changing value using reflection
Field f = ImmutableWithoutMutator.class.getDeclaredField("age");
f.setAccessible(true);
f.set(immMutator, 2000);
System.out.println(immMutator);
}
}
My question is, I have not modified the Modifiers for the fields using reflection API. Then how the code is still able to mutate final fields?