OscarRyz
OscarRyz

Reputation: 199225

Why am I getting an empty array of annotations here

According to the doc and to this answer I should be having "Override" (or something similar) in the following code:

import java.lang.reflect.*;
import java.util.*;
import static java.lang.System.out;
class Test { 
  @Override
  public String toString() { 
    return "";
  }
  public static void main( String ... args ) { 
    for( Method m : Test.class.getDeclaredMethods() ) { 
      out.println( m.getName() + " " + Arrays.toString( m.getDeclaredAnnotations()));
    }
  }
}

But, I'm getting an empty array.

$ java Test
main []
toString []

What am I missing?

Upvotes: 4

Views: 1005

Answers (2)

hoipolloi
hoipolloi

Reputation: 8044

I wrote this example to help me understand skaffman's answer.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.Arrays;

class Test {

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

    @Foo
    public static void main(String... args) throws SecurityException, NoSuchMethodException {
        final Method mainMethod = Test.class.getDeclaredMethod("main", String[].class);

        // Prints [@Test.Foo()]
        System.out.println(Arrays.toString(mainMethod.getAnnotations()));
    }
}

Upvotes: 0

skaffman
skaffman

Reputation: 403481

Because the @Override annotation has Retention=SOURCE, i.e. it is not compiled into the class files, and is therefore not available at runtime via reflection. It's useful only during compilation.

Upvotes: 6

Related Questions