Annotations are not read correctly

Hi, I have the following sample Annotation

package annotations;

import java.lang.annotation.Annotation;

/**

* @author Stefan Schuster

*

* TODO To change the template for this generated type comment go to

* Window - Preferences - Java - Code Style - Code Templates

*/

public @interface NoticeAnnotation {

String name() default "anonymous";

String note() default "TODO";

}

And the following class that uses the annotation:

public class AnnotationsTest {

public static void main(String[] args) {

for(Method m : AnnotationsTest.class.getMethods())

{

if(m.isAnnotationPresent(NoticeAnnotation.class))

{

// Die Annotation ist vorhanden, auslesen des Methodennamens und

// der Parameter der Annotation

System.out.println("Die Methode " + m + " ist mit einer Notiz versehen:");

NoticeAnnotation na = m.getAnnotation(NoticeAnnotation.class);

System.out.println("Der Entwickler " + na.name() + " hat eine Notiz eingef齡t:");

System.out.println(na.note());

}

}

}

@NoticeAnnotation(

name = "Dagobert Developer",

note = "Diese Methode muss noch verbessert werden"

)

public void testMethode()

{

// not relevant

}

}

The problem is that the annotation is not found for any method, so the

part where the information about the annotation is printed is never called.

What am I missing, to me it looks like the sample from the annotations tutorial,

but it is not working...

Thanks in advance,

Stefan

[1649 byte] By [stscit04] at [2007-9-30 19:37:56]
# 1

Add @Retention to your annotation:

[code]

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)

public @interface NoticeAnnotation {

String name() default "anonymous";

String note() default "TODO";

}

[code]

That directs the JRE to read the annotation into memory at run time, so it can be found by reflection.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/class-use/Retention.html

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/RetentionPolicy.html

sjasja at 2007-7-7 0:22:55 > top of Java-index,Java Essentials,Java Programming...
# 2
Thank you very much, it works!Looks like this should be clarified in the tutorial....Regards,Stefan
stscit04 at 2007-7-7 0:22:55 > top of Java-index,Java Essentials,Java Programming...
# 3
Ouch... Looks more like I should learn to read.... It IS covered in thetutorial, sorry....Regards,Stefan
stscit04 at 2007-7-7 0:22:55 > top of Java-index,Java Essentials,Java Programming...