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:

public @interface Autowired {

The Target BTW restricts this annotation so it can only be applied to a class.

Very useful stuff :)

- 2 comments by 1 or more people Not publicly viewable

  1. RayKrueger

    Don't forget to annotate your annotation as @java.lang.annotation.Inherited

    Redundant redundancy always comes out when creating annotations…

    The Inherited annotation means that subclasses should Inherit this annoation from the superclass.

    21 Feb 2006, 21:11

  2. Cheers Ray.

    Good call.

    21 Feb 2006, 22:05

Add a comment

You are not allowed to comment on this entry as it has restricted commenting permissions.

February 2006

Mo Tu We Th Fr Sa Su
Jan |  Today  | Mar
      1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28               

Search this blog



Most recent comments

  • Interesting… While I'm not completely convinced in such microbenchmarks, I'm pretty sure that 1ms … by Alexander Snaps on this entry
  • Hello. I bought the book yesterday. I was trying to find the source code for chapter 11 and chapter … by Suleman on this entry
  • http://woosight.net/account/login?username=demo by live mashup demo on this entry
  • Thanks mate ….. This blog was really helpful. by Maaz Hurzuk on this entry
  • Ty. Not directly helpful for my problem, but pointed me in the right direction. You will also get th… by Mike E. on this entry

Blog archive

Not signed in
Sign in

Powered by BlogBuilder