What Are Code Annotations?

If you write Java code and document your code (one doesn’t necessarily imply the other, sadly), you are already familiar with a particular kind of code annotation: Javadoc tags. With Javadoc, you put metadata about the code (like the author, references to other related classes, and descriptions of the meanings of methods) into the code itself, in the form of annotations. You then run a tool (in this case, the Javadoc generator) over the code to generate HTML documentation from these annotations.

Generalized annotation schemes follow this same basic model. The difference is that you can do much more than just generate documentation (as useful as that is). Code annotations can be used to generate deployment descriptors, configuration files, and even Java code, as shown in Figure 21-1.

General model for code annotations

Figure 21-1. General model for code annotations

As depicted in the figure, annotations are inserted as markup directly in your code. As an example, here’s an XDoclet annotation specifying some deployment settings for a web component:

/**
 * @web.servlet
 *     name="ShoppingCart"
 *     display-name="The Shopping Cart Servlet"
 */
public class ShoppingCartServlet extends HttpServlet {
    . . .
}

When you’re dealing with enterprise development scenarios, annotating your code in a structured way can benefit you in a number of ways:

Reduce development effort

An annotation system allows you to mark up ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.