3

When using the Java reflections library I can correctly find classes decorated with an annotation:

Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(CommandName.class);

but when I try to see how many annotations are on each class I always see zero:

for(Class c : annotated)
{
     int numAnnotations = c.getAnnotations().length;
}

Why does c.getAnnotations() return an array of length 0? In fact, in the debugger, all the fields (except name) of c are null.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Dejas
  • 3,511
  • 4
  • 24
  • 36
  • Regarding your final sentence, I think much of the metadata within `Class` instances is lazily loaded. – Paul Bellora Nov 13 '12 at 20:51
  • Under this assumption should not calling getAnnotations() for the first time force at least the annotations array to populate? – Dejas Nov 13 '12 at 20:55
  • Yeah, that should definitely happen. I just meant that the debugger was probably misleading. +1 to your question. – Paul Bellora Nov 13 '12 at 21:18

1 Answers1

0

Ack, turns out annotations aren't preserved to runtime unless you mark them with @Retention(RetentionPolicy.RUNTIME). This fixed it. Strange that the class was included in the set though. I would think it would be all or nothing.

Dejas
  • 3,511
  • 4
  • 24
  • 36