我正在将此代码运行到junit测试中。但是,没有找到注释,也没有输出任何内容。什么可能导致这种情况。
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Datafield {
}
public class EntityTest
{
@Datafield
StandardFieldText username;
@Test
public void TestEntityAnnotation() throws NoSuchFieldException, SecurityException
{
EntityTest et = new EntityTest();
Annotation[] annos = et.getClass().getAnnotations();
for(Annotation a : annos)
System.out.println(a);
}
}
答案 0 :(得分:2)
您正在请求EntityTest
类的注释,这些注释确实没有注释。
为了获得该字段上方的注释,您应该尝试:
Field f = ep.getDeclaredField("username");
Annotation[] annos = f.getDeclaredAnnotations();
答案 1 :(得分:1)
您请求了类本身的注释。您应该遍历方法,字段等,以检索这些元素的注释:http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
例如:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Datafield {
}
public class EntityTest
{
@Datafield
StandardFieldText username;
@Test
public void TestEntityAnnotation() throws NoSuchFieldException, SecurityException
{
EntityTest et = new EntityTest();
for(Method m : et.getClass().getDeclaredMethods()) {
Annotation[] annos = m.getDeclaredAnnotations();
for(Annotation a : annos)
System.out.println(a);
}
}
}