Java 5 and above supports the use of annotations to include metadata within programs. Groovy 1.1 and above also supports such annotations.
Annotations are used to provide information to tools and libraries. They support declarative style of providing information directly in the source code. Such information would need to otherwise be provided using non-declarative means or using external files.
As an example, suppose you had the following Java Annotation definition:
You could use this annotation in a Groovy file as follows:
Now if you had tools or libraries which understood this annotation, you could process this source file (or the resulting compiled class file) and perform operations based on this metadata.
As another example, consider this XStream example. XStream is a library for serializing Java (and Groovy) objects to XML. Here is an example of how you could use it without annotations:
This results in the following code:
We can also use annotations with XStream as follows:
This results in the following output:
Annotations are also used in the following examples: