All entries for Monday 13 February 2006
February 13, 2006
helloworld annotation
So I wanted to play around with Annotations, so I decided to do a hello world.
Actually, the use case is I wanted to mark hibernate backed objects as needing to be autowired by Spring.
I created my annotation
public @interface Autowired {
}
and updated my class:
@Autowired public class MyClass {
}
and nothing. The unit test failed:
MyClass cf = new MyClass();
Class class1 = cf.getClass();
// assertTrue(class1.isAnnotationPresent(Autowired.class));
Annotation[] anns = class1.getAnnotations();
assertEquals(1, anns.length);
No idea why, thinking it might be a class path issue with Eclipse, I recompiled, but still nothing.
As it turns out, you need to annotate your annotations :) You need to tell the compiler how to retain the annotations (link).
Specifying that the annotations must be retained for runtime retrieval means it now works:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {
}
The Target BTW restricts this annotation so it can only be applied to a class.
Very useful stuff :)