Check Java Classes Immutability in Runtime
Annotate your class with @Immutable
annotation and its immutability will be checked when instantiated:
@Immutable public class Foo { private String data; // This class is NOT immutable. }
During instantion of this class, a runtime exception will be thrown because it is mutable.
Keep in mind that, although JDK requires some classes to be immutable, most of them are mutable in reality. For example, BigDecimal
. (Well, at least in OpenJDK 7). Our immutability checker is rather strict and doesn't allow classes to have any non-private, non-final properties in order to be called truly immutable.
If your class/interface has a property with a type that is an interface, that child interface has to be annotated with @Immutable
. For example:
@Immutable public class Foo { // This class is NOT immutable because we can't guarantee // that an immutable implemenation of DateFormat will be // used in all its implementations. private final DateFormat format; }
Although in Java, a final
array can change its elements, we assume that private
and final
arrays are immutable:
@Immutable public class Foo { // This class is immutable, although Java allows you to change // elements of this array in runtime. private final int[] data = new int[] {1, 2, 3}; public void set(int idx, int value) { this.data[idx] = value; } }
The mechanism is implemented with AOP/AspectJ. Read how to integrate it into your pom.xml
.
This blog post explains why objects should be immutable.