Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getAnnotations() is empty

I would like to use annotations in my application. For this reason I create "hello world" for annotations:

follows example:

public class HelloAnnotation
{
    @Foo(bar = "Hello World !")
    public String str;

    public static void main(final String[] args) throws Exception
    {
        System.out.println(HelloAnnotation.class.getField("str").getAnnotations().length);
    }
}

And this is the Annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
public @interface Foo
{
    public String doTestTarget();
}

My problem is now that getAnnotations() in main is empty. What is wrong with my code?

like image 238
Walery Strauch Avatar asked Sep 28 '12 14:09

Walery Strauch


1 Answers

Add the following to your annotation:

    @Retention(RetentionPolicy.RUNTIME)

From the javadoc for @Retention:

the retention policy defaults to RetentionPolicy.CLASS

From the javadoc for RetentionPolicy:

  • CLASS
    • Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
  • RUNTIME
    • Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
  • SOURCE
    • Annotations are to be discarded by the compiler.
like image 187
David Grant Avatar answered Sep 20 '22 09:09

David Grant