Table of Contents

Java - Annotations

About

Since Java version 1.5.

An annotation is an element of the java programming language (modifier or Metadata tag) that can be associated with:

A metadata annotation represents a Java language feature that lets you attach structured and typed metadata to the source code. Annotations alone are sufficient for the metadata specification–you do not need to use XML deployment descriptors

With Java EE annotations, the standard deployment descriptors (application.xml and web.xml) are optional.

Java EE 5 defines a number of annotations that can be injected into your source code. To declare an annotation, you simply precede the keyword with an “at” sign (@).

Annotations look like this:

@annotation-name ( parameters )

The call is similar to method calls except that they begin with @.

An annotation applies to a class or method and directly precedes the class or method definition.

They annotate the class or method with metadata, replacing configuration files.

Annotations replace boilerplate code, common code that is required by certain applications.

For example, an annotation can replace:

For example, annotations can replace the need for a separately maintained deployment descriptor for JavaBeans™.

Annotations:

Annotations have a number of uses, among them:

Advantages and Disadvantages

of Using Annotations

Metadata annotations are relatively simple to use and understand. They provide in-line metadata located with the code that this metadata is describing–you do not need to replicate the source code context of where the metadata applies.

On the other hand, annotations unnecessarily couple the metadata to the code. Thus, changes to metadata require changing the source code.

of Using XML

The following are advantages of using XML:

The main disadvantages of mapping with XML are the complexity and the need for replication of the code context.

Task

Java EE 5 provides annotations for the following tasks, among others:

How to

Create an annotation

Suppose that a software group has traditionally begun the body of every class with comments providing important information:

public class Generation3List extends Generation2List {

   // Author: John Doe
   // Date: 3/17/2002
   // Current revision: 6
   // Last modified: 4/12/2004
   // By: Jane Doe
   // Reviewers: Alice, Bill, Cindy

   // class code goes here

}

To add this same metadata with an annotation, you must first define the annotation type. The syntax for doing this is:

@interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   String[] reviewers();  // Note use of array
}

Specification

Java™ EE 6 and Java EE 5 define a number of types or groups of annotations, defined in a number of Java Specification Requests (JSRs).

Java EE 5 defines the following types of annotations:

Documentation / Reference