How to Annotate an Immutable Class in Java

documentationimmutabilityjava

I recently stumbled upon how useful immutable objects are and that e.g. if you pass elements to a constructor and your class should be immutable, you have to copy these elements if they are not immutable themselves.

This requires a lot of checking or knowledge about my project, because if I have

public A(B foo)

and B is not immutable, A I'd have to copy B. Now imagine B seems immutable, but itself has mutable classes in the constructor and so on.

Is there a standard or best-practice for documenting if a class is immutable in Java? It seems there is no @immutable keyword in Javadoc.

The @Immutable annotation seems to be something totally different for auto class generation and not part of standard Java.

Best Answer

Looking at the documentation of the String class (bold text is something I did):

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

As you can see, there is no particular labeling or other markers, however, they do specify in the JavaDoc describing the class that the String class represents a constant, immutable object.

Thus, assuming that you followed the instructions provided in this Oracle tutorial to create an immutable class, to make sure that the immutability of the class is documented, you should just make sure you mention in it the in the JavaDoc describing the class and what it does.

If that still does not suit what you need, you could take a look at how you could build custom JavaDoc tags here.

Related Topic