All 2 entries tagged Annotations
No other Warwick Blogs use the tag Annotations on entries | View entries tagged Annotations at Technorati | There are no images tagged Annotations on this blog
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 :)
February 03, 2006
JDK5 Annotations; I love them, no, I hate them! (Actually I hate Eclipse) :)
So there is a fantastically useful annotation: @Override which when indicates that a particular method is overriding a method in the super class.
Why is this useful?
Assume today we are overriding the method called "methodA", tomorrow we get a new release of the library and the method in the parent class is no longer called "methodA", but renamed to "methodWithAMuchBetterName".
Your code is syntactically correct; it will compile, but it is not semantically correct. The no longer overridden method fails. No compiler errors to help you out; nothing.
You may argue that if you are overridding a method you almost certainly want to be calling super.sameMethod(); but that is just wrong. You do not have to , nothing in the million + 1 best practices suggest it, it is one of the more annoying anti-patterns. In particular; a lot of framework provide template method which do absolutely nothing for the sole purpose of you extending them; or they provide abstract methods for the same purpose.
Anyways; so JDK5 introduced an Annotation which told the compiler that the method is overridding a parent method. If the method in the super class is removed; your code won't compile.
Excellent. Lovely. As well as adding extra documentation to the source code; it has empowering side effects.
So sure; I love JDK annotations.
Now I implement an interface; create a method which implements the interface, stick an "@Override" on the method, and what happens? Eclipse moans that the method must override a superclass method.
ARRRGGHHH!!!!! It still compiles, but the source code looks like it is incorrect code.
Poo.