80

I create my annotation

public @interface MyAnnotation {
}

I put it on fields in my test object

public class TestObject {

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

Now I want to get list of all fields with MyAnnotation.

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

But seems like my block do action is never executed, and fields has no annotation as the following code returns 0.

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

Is anyone can help me and tell me what i'm doing wrong?

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
user902383
  • 8,420
  • 8
  • 43
  • 63
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) Please add an upper case letter at the start of sentences. Also use a capital for the word I & proper names like Java, and abbreviations and acronyms like JEE or WAR. This makes it easier for people to understand and help. – Andrew Thompson May 16 '13 at 10:52
  • possible duplicate of [How to get annotations of a member variable?](http://stackoverflow.com/questions/4453159/how-to-get-annotations-of-a-member-variable) – fglez May 17 '13 at 11:43

2 Answers2

88

You need to mark the annotation as being available at runtime. Add the following to your annotation code.

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
Zutty
  • 5,357
  • 26
  • 31
19
/**
 * @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;
}
Mindaugas K.
  • 433
  • 5
  • 12
  • 56
    Apache Commons has this functionality: FieldUtils.getFieldsListWithAnnotation(...) – DBK Jan 24 '17 at 15:43