getAnnotations() 为空

getAnnotations() empty

我有以下代码:

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

和这个失败测试:

@MyAnnotation
private Object obj = new Object();

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

导致:

java.lang.AssertionError: 
Expected :1
Actual   :0

您将注释添加到 class 中的 Field 而不是 Object class。尝试

Field field = getClass().getDeclaredField("obj");
MyAnnotation ma = field.getAnnotation(MyAnnotation.class);
assertNotNull(ma);
assertEquals(1, field.getAnnotations().length);

看看How to get annotations of a member variable?

obj.getClass() returns 在你的例子中 java.lang.Object 没有任何注释。