THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Chapter 15. Annotations


I don't like spinach, and I'm glad I don't, because if I liked it I'd eat it, and I just hate it.

Clarence Darrow

The source code for our programs is usually accompanied by copious amounts of informal documentation that
typically is contained within comments in the source code file. For example, many organizations have a
standard preamble that they place at the top of class source files that contains things like copyright
information, the programmers name, the date the class was created, the date the class was last modified, the
current revision number, and so forth. Other comments may reflect intended usage of a class or a method, or
usage limitations, such as documenting that the instances of a class are not thread-safe and so shouldn't be
used concurrently. Other comments may be provided for processing by external tools that assist in the
management and deployment of an application, such as version control in a source code management system,
or deployment descriptors on how a class should be managed by an application server. These comment-based
annotations serve a useful purpose, but they are informal and ad hoc. A better way to document these things is
to annotate the program elements directly using annotation types to describe the form of the annotations.
Annotation types present the information in a standard and structured way that is amenable to automated
processing by tools.


While this chapter presents the syntax and semantics of using annotations and defining annotation types, it
can't tell you what annotations to use when because very few such annotations exist within the language. The
annotations you use will be those supported by the tools in your development or deployment environment.
Annotation is centered on types in the package java.lang.annotation, and the standard types
introduced in this chapter come from this package.


15.1. A Simple Annotation Example


Consider an informal, comment-based class preamble:


/-------------------------------
Created: Jan 31 2005
Created By: James Gosling
Last Modified: Feb 9 2005
Last Modified By: Ken Arnold
Revision: 3
---------------------------------
/
public class Foo {
// ...
}


You can define an annotation type that can hold all of the desired information:


@interface ClassInfo {
String created();
String createdBy();
String lastModified();
String lastModifiedBy();
int revision();
}

Free download pdf