Learn to Use the New Annotation Feature of Java 5.0 : Page 2

Developers have always struggled to find ways of adding semantic data to their Java code. They had to: Java didn't have a native metadata facility. But that's all changed with version 5.0 of Java, which allows annotations as a typed part of the language.

by Javid Jamae

Feb 10, 2005

Page 2 of 4

Annotating Code
Annotations fall into three categories: normal annotations, single member annotations, and marker annotations (see Table 1). Normal and single member annotations can take member values as arguments when you annotate your code.

Category

Example

Normal AnnotationsAnnotations that take multiple arguments. The syntax for these annotations provides the ability to pass in data for all the members defined in an annotation type.

Marker AnnotationsThese annotations take no parameters. They are used to mark a Java element to be processed in a particular way.

@Deprecated
public void doWork() { ... }

Any Java declaration can be marked with an annotation. That is, an annotation can be used on a: package, class, interface, field, method, parameter, constructor, enum (newly available in Java 1.5), or local variable. An annotation can even annotate another annotation. Such annotations are called meta-annotations.

As you can see in the ClassLevelAnnotation, annotations may also take arrays of values. When creating an annotation that requires an array you must surround the array of parameters with brackets ( { … } ) and you must comma-separate each array parameter.

Annotation types may define default values for some members. Every member-value pair that does not have a default value must be supplied when you create an annotation.

The annotation-type declaration below uses meta-annotations, which provide information on how the annotation type can be used:

This code shows how to use meta-annotations when declaring your own annotation type. I will cover the specifics on declaring annotation types and meta-annotation types later, but for now, just know that you can use meta-annotations to annotate other annotations.

Packages annotations are also allowed, but because packages are not explicitly declared in Java, package annotations must be declared in a source file called package-info.java in the directory containing the source files for the package. This file should contain only a package declaration, preceded by any annotations that should apply to the package. This java file must not contain an actual class definition (which would be illegal anyways, because package-info is not a legal identifier).