1

I have the following code:

import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}

and this failing test:

@MyAnnotation
private Object obj = new Object();

@Test
public void test() throws Exception {
    assertEquals(1, obj.getClass().getAnnotations().length);
}

resulting in:

java.lang.AssertionError: 
Expected :1
Actual   :0
gurghet
  • 7,591
  • 4
  • 36
  • 63

2 Answers2

2

You added the annotation to the Field in your class not the Object class. Try

Field field = getClass().getDeclaredField("obj");
MyAnnotation ma = field.getAnnotation(MyAnnotation.class);
assertNotNull(ma);
assertEquals(1, field.getAnnotations().length);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thank you! That is the correct answer, but how would you go about not using `getDeclaredField`? I mean, is there any way to naturally pass a “special” annotated object without resorting to reflective functions? – gurghet Jul 31 '15 at 11:56
  • @gurghet `Class`, `Method`, `Field` are all part of reflection. You can read the raw byte code to find the annotation (and some tools do this) but this is a lot harder. – Peter Lawrey Jul 31 '15 at 17:43
1

Look at How to get annotations of a member variable?.

obj.getClass() returns in your case java.lang.Object that does not have any annotations.

Community
  • 1
  • 1
Zaimatsu
  • 66
  • 15