Java Annotations not working ???

C

chvid

Why - oh why - does the following code not output the annotation
attached to method test?

import java.lang.reflect.Method;
import java.lang.annotation.Annotation;

@interface AnnTest {
String value();
}

interface Test {
@AnnTest("hello")
void test();
}

public class Main {
public static void main(String args[]) {
for (Method m : Test.class.getMethods()) {
System.out.println("method is "+m.getName());
for (Annotation a : m.getAnnotations())
System.out.println(" annotation is "+a);

}
}
}

-- Christian
Please use the email-address at my homepage:
http://vredungmand.dk
 
T

Tony Morris

Why - oh why - does the following code not output the annotation
attached to method test?

import java.lang.reflect.Method;
import java.lang.annotation.Annotation;

@interface AnnTest {
String value();
}

interface Test {
@AnnTest("hello")
void test();
}

public class Main {
public static void main(String args[]) {
for (Method m : Test.class.getMethods()) {
System.out.println("method is "+m.getName());
for (Annotation a : m.getAnnotations())
System.out.println(" annotation is "+a);

}
}
}

-- Christian
Please use the email-address at my homepage:
http://vredungmand.dk


Because it has the default retention policy.

Try this:
@Retention(RetentionPolicy.RUNTIME)
@interface AnnTest {
// blah blah
 
C

Chris Uppal

Why - oh why - does the following code not output the annotation
attached to method test?
[...]

I think you need to specify that the annotation is retained at runtime. By
experiment, I find that changing the declaration of AnnTest to read:

@Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
@interface AnnTest
{
String value();
}

will fix it, but I don't know if that's the way we're intended to do it.

Without that (or whatever the correct equivalent is) the annotations are still
created but default to CLASS retention -- which means that the annotations are
present in the classfile, but are stored as 'RuntimeInvisibleAnnotations'
attribues (instead of 'RuntimeVisibleAnnotations') which are discarded by the
JVM and/or ignored by the reflective stuff.

The whole annotations thing seems way overcomplicated to me.

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top