Get list of fields with annotation, by using reflection

前端 未结 2 1473
情书的邮戳
情书的邮戳 2020-12-05 09:42

I create my annotation

public @interface MyAnnotation {
}

I put it on fields in my test object

public class TestObject {

          


        
相关标签:
2条回答
  • 2020-12-05 09:49

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

    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyAnnotation {
    }
    
    0 讨论(0)
  • 2020-12-05 10:10
    /**
     * @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;
    }
    
    0 讨论(0)
提交回复
热议问题