如何获取接口实现类的注释

时间:2017-06-25 09:00:23

标签: java annotations code-injection

我希望类 PersonCollector 通过具有注释 PersonResolver 的特定类注入字段。 PersonCollector 检查带注释的类是否具有等于 PersonCollector.personType 字段的注释值。如果符合,逻辑将添加实现拥有此批注的类,并将其分配给 PersonCollector.personByType 字段。

我的问题是,我有一个界面和两个实施类 CoolPerson & UncoolPerson 都使用 @PersonResolver 注释进行注释,并使用枚举 PersonType 指定其类型的值。

查找包含特定界面的所有实现的唯一方法是调用 Person ,即Person.class.getAnnotations()。遗憾的是,这只会产生在Person接口上声明的注释。

这不是我真正想要的。我想要一个拥有Annotation的 Person 的所有实现的列表 - 而不是Person本身。

这是我想要实现的伪/划痕代码:

@PersonResolver

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonResolver {
  PersonType value();
}

两种实现

@PersonResolver(PersonType.COOL)
public class CoolPerson implements Person {
  // implementation
}

@PersonResolver(PersonType.UNCOOL)
public class UncoolPerson implements Person {
  // implementation
}

PersonCollector

public class PersonCollector {
  private PersonType personType;
  private Person personByType;

  public PersonCollector(PersonType personType) {
    this.personType = personType; // PersonType.COOL

    Annotation[] annotations = Person.class.getDeclaredAnnotation(PersonResolver.class);

    // What I'd like to get are ALL classes that implement the "Person" interface
    // and have the "PersonResolver" Annotation.

    // PseudoCode!
    if (annotations[0].value == personType) {
      this.personByType = annotations[0].getClassThatImplementsMe(); // CoolPerson instance is assigned to the field
    }
  }
  // ...
}

1 个答案:

答案 0 :(得分:1)

您可以使用Reflections等库来扫描类路径,以查找使用PersonResolver注释的类型。例如,以下代码将返回一组java.lang.Class es注释@PersonResolver,其value()属性等于personType

Reflections reflections = new Reflections(("com.myproject"));
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(PersonResolver.class)
        .stream()
        .filter(c -> c.getAnnotation(PersonResolver.class).value() == personType)
        .collect(Collectors.toSet());
相关问题