January 4, 2006

Java 5.0 annotations

I've finally got around to looking at some of the new features in Java 5.0. When Java 5.0 first came out, it seemed like the new features were mostly Java (ironically) catching up with C#. (BTW - my background includes several years of Java, then some C#, then some more Java, then some more C# and currently Java again).

What I've seen so far looks good, but there are some things that I'd have preferred to be slightly different. This article is about Annotations, and I might write future articles on other of the new features in Java 5.0.

Annotations allow you to add metadata, examples include object/relational mapping and specifying test methods. I won't go into details here - just a simple example (it's left to the interested reader to find out more).

Defining an annotation type

To define an annotation type called Meta:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Meta {
	String data() default "fast";
}

Using an annotation

To use that annotation:

...
	@Meta(data = "slow") 
	public void foo(){
...
	}
...

Using the annotation meta data ("calm down dear, it's only an example").

To print out the meta data that the annotation defines for the example above:

	public static void main(String[] args) {
		for (Method method : MyClass.class.getMethods()) {
			Annotation[] annotations = method.getAnnotations();
			int num = annotations.length;
			if(num==1){
				System.out.println(((Meta)annotations[0]).data());
			}
		}
	}

@Retention Gotcha

When defining an annotation type, you can specify when the annotation should be available; in a nutshell, before compilation (RetentionPolicy.SOURCE), after compilation (RetentionPolicy.CLASS) or at runtime (RetentionPolicy.RUNTIME). The default is RetentionPolicy.CLASS - not what I would have expected. My guess is that the main use of annotations will be for metadata that you want available at runtime, and certainly the examples that I've seen so far are nearly all runtime.

Syntax Gotcha

The fact that the syntax looks so similar for an annotation type compared to an interface - only an "@" different - I think is more confusing than helpful. An annotation type cannot extend or implement anything. The "attributes" (things that look like method declarations) cannot have parameters. Also, as you can see from the example above, annotation types implicitly, rather than explicity, implement "Annotation".

Posted by ivan at January 4, 2006 4:53 PM
Copyright (c) 2004-2008 Ivan Moore