getFieldsAnnotatedWith包含的注释

时间:2013-05-02 21:00:49

标签: java reflection annotations

注释

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Searchable {
    SearchType[] types() default { SearchType.ALL };
}

某些方法的反思

Reflections reflections = new Reflections(packageName);
reflections.getFieldsAnnotatedWith(); // Here's the problem

我想返回所有注明了Searchable 至少包含SearchType.ALL 的字段。我尝试使用此方法定义new Searchable() { ... }。虽然这会导致只有完全匹配的字段。例如。仅包含SearchType.ALL。这样:

new Searchable() {
        @Override public SearchType[] types() { return { SearchType.ALL }; }
        @Override public Class<? extends Annotation> annotationType() { return Searchable.class; }
        }

我希望@Searchable(types = { SearchType.ALL, SearchType.TEXT })的字段也成为热门,因为它包含SearchType.ALL。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

我对Reflections API了解不多,但您可以简单地使用Searchable注释获取所有注释的字段,然后检查它们的Searchable注释类型是否包含SearchType.ALL:

Set<Field> fields = reflections.getFieldsAnnotatedWith(Searchable.class);
Set<Field> wanted = new HashSet<Field>();
for (Field field : fields) {
    Searchable annotation = field.getAnnotation(Searchable.class);
    if (Arrays.asList(annotation.types).contains(SearchType.ALL)) {
        wanted.add(field);
    }
}