我想设计一个类来逐步展示不变性。
以下是一个简单的类
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);
}
}
现在我仍然可以通过使用以下代码来使用反射。
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);
}
}
我的问题是,我没有使用反射 API 修改字段的修饰符。那么代码如何仍然能够改变最终字段?