Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Annotations not working

Tags:

I'm trying to use Java annotations, but can't seem to get my code to recognize that one exists. What am I doing wrong?

  import java.lang.reflect.*;   import java.lang.annotation.*;    @interface MyAnnotation{}     public class FooTest   {      @MyAnnotation     public void doFoo()     {            }      public static void main(String[] args) throws Exception     {                        Method method = FooTest.class.getMethod( "doFoo" );          Annotation[] annotations = method.getAnnotations();         for( Annotation annotation : method.getAnnotations() )             System.out.println( "Annotation: " + annotation  );      }   } 
like image 719
Rexsung Avatar asked Apr 08 '09 05:04

Rexsung


People also ask

How are annotations executed in Java?

Annotations don't execute; they're notes or markers that are read by various tools. Some are read by your compiler, like @Override ; others are embedded in the class files and read by tools like Hibernate at runtime.

Do Java annotations do anything?

Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code, although some types of annotations can actually be used for that purpose.


2 Answers

You need to specify the annotation as being a Runtime annotation using the @Retention annotation on the annotation interface.

i.e.

@Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation{} 
like image 87
James Davies Avatar answered Oct 12 '22 23:10

James Davies


Short answer: you need to add @Retention(RetentionPolicy.RUNTIME) to your annotation definition.

Explanation:

Annotations are by default not kept by the compiler. They simply don't exist at runtime. This may sound silly at first, but there are lots of annotations that are only used by the compiler (@Override) or various source code analyzers (@Documentation, etc).

If you want to actually USE the annotation via reflection like in your example, you'll need to let Java know that you want it to make a note of that annotation in the class file itself. That note looks like this:

@Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation{} 

For more information, check out the official docs1 and especially note the bit about RetentionPolicy.

like image 23
Brandon Yarbrough Avatar answered Oct 13 '22 01:10

Brandon Yarbrough