28

Here is a test class:

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

public class TestAnnotations {

    @interface Annotate{}

    @Annotate public void myMethod(){}

    public static void main(String[] args) {
        try{
            Method[] methods = TestAnnotations.class.getDeclaredMethods();
            Method m = methods[1];
            assert m.getName().equals("myMethod");

            System.out.println("method inspected ? " + m.getName());
            Annotation a = m.getAnnotation(Annotate.class);
            System.out.println("annotation ? " + a);
            System.out.println("annotations length ? "
                + m.getDeclaredAnnotations().length);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Here is my output :

method inspected ? myMethod
annotation : null
annotations length : 0

What I am missing to make annotations visible through reflection ?
Do I need an annotation processor even for just checking their presence ?

1 Answer 1

42

In order to access an annotation at runtime, it needs to have a Retention policy of Runtime.

@Retention(RetentionPolicy.RUNTIME) @interface Annotate {}

Otherwise, the annotations are dropped and the JVM is not aware of them.
For more information, see here.

2
  • May I ask, though, if you happen to know whether there is a way to change the default behaviour of CLASS retention policy to RUNTIME ?
    – glmxndr
    Feb 18, 2010 at 8:14
  • Only by recompiling the annotation. If it's not your annotation, no.
    – user207421
    Feb 18, 2010 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.