java - 如何获取接口(interface)实现类的注解

标签 java annotations code-injection

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

我的问题是,我有一个接口(interface)Person和两个实现类CoolPersonUncoolPerson,两者都用@注释PersonResolver 注释和一个使用枚举 PersonType 指定其类型的值。

查找持有特定接口(interface)的所有实现的唯一方法是调用 Person,即 Person.class.getAnnotations()。不幸的是,这仅产生在 Person 接口(interface)上声明的注释。

这不是我真正想要的。我想要一个拥有注释的 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
}

人物收集器

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
    }
  }
  // ...
}

最佳答案

您可以使用诸如Reflections之类的库它将扫描类路径中使用 PersonResolver 注释的类型。例如,以下代码将返回一组用 @PersonResolver 注解的 java.lang.Class,其 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());

关于java - 如何获取接口(interface)实现类的注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744798/

相关文章:

php - 使用 MySQLi 时如何防止 SQL 注入(inject)?

java - 级联教程字数统计示例错误

java - 如何编写 Hibernate HQL 查询来删除所有 "grand children"元素?

jsf - ResourceDependency 注释在 UIComponent 中不起作用,并在 src 中生成 "RES_NOT_FOUND"错误

Spring MVC : @RequestBody VS @ModelAttribute

sql - 如何为 SQL LIKE 转义用户输入中的特殊字符?

ejb 方法调用期间出现 java.lang.VerifyError

java - 服务器端java小程序...如何创建?

初始化上下文时java.lang.NoClassDefFoundError : org. springframework.beans.FatalBeanException

javascript - 自动将 HTML 插入页面上某些点的代码?