Tuesday, December 9, 2008

Creating a Java annotation

So I created a new (method-level) annotation that basically just takes a string, and when the target method is invoked, via aspect I get that string. The annotation looks like this (name changed to protect the innocent):

public @interface Annotatable { String value(); }

After a few hours of banging my head, trying to figure out why everything compiled correctly, yet when testing I could never get the find the annotation on the target method. Turns out, this was soooo poorly documented by Sun/Java gods, you need to annotate your annotation, like this:

import java.lang.annotation.*;


The RetentionPolicy enum tells the compiler to keep the annotation around AFTER you compile, instead of throwing it away (like it does by default). The Target annotation tells the compiler which types of elements your annotation can apply to (classes, methods, params, all, etc.). The long and short of it is: don't forget to annotate your annotations.