2013-05-16 68 views
38

创建我的注释获取与注释,字段列表通过使用反射

public @interface MyAnnotation { 
} 

我把它放在场在我的测试对象

public class TestObject { 

    @MyAnnotation 
    final private Outlook outlook; 
    @MyAnnotation 
    final private Temperature temperature; 
    ... 
} 

现在,我想所有的字段列表MyAnnotation

for(Field field : TestObject.class.getDeclaredFields()) 
{ 
    if (field.isAnnotationPresent(MyAnnotation.class)) 
     { 
       //do action 
     } 
} 

但好像我的块做永远不会执行的动作和字段没有注释如下面的代码返回0

TestObject.class.getDeclaredField("outlook").getAnnotations().length; 

是任何人都可以帮助我,告诉我,我在做什么错误?

+0

1)为了更好地帮助越早,张贴[SSCCE](http://sscce.org/)。 2)请在句子开头添加大写字母。还要使用大写字母I和专有名称(如Java),以及缩写和首字母缩略词(如JEE或WAR)。这使人们更容易理解和帮助。 –

+0

[How to get annotations of a member variable?](http://stackoverflow.com/questions/4453159/how-to-get-annotations-of-a-member-variable) – fglez

回答

54

您需要将注释标记为在运行时可用。将以下内容添加到注释代码中。

@Retention(RetentionPolicy.RUNTIME) 
public @interface MyAnnotation { 
} 
+0

这是正确的。但是,我认为Annotation适合运行时使用。 – wrivas

+3

@wrivas并非所有的注释都是针对运行时的。例如'@ SuppressWarnings'是RetentionPolicy.SOURCE,因为它只是提示编译器不警告某些事情。 – Patrick

+0

注解仅用于源代码(供您阅读),编译时或运行时 – 2016-04-01 02:11:30

6
/** 
* @return null safe set 
*/ 
public static Set<Field> findFields(Class<?> classs, Class<? extends Annotation> ann) { 
    Set<Field> set = new HashSet<>(); 
    Class<?> c = classs; 
    while (c != null) { 
     for (Field field : c.getDeclaredFields()) { 
      if (field.isAnnotationPresent(ann)) { 
       set.add(field); 
      } 
     } 
     c = c.getSuperclass(); 
    } 
    return set; 
} 
+11

Apache Commons具有此功能:FieldUtils.getFieldsListWithAnnotation(...) – DBK