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

Java 如何获取接口实现类的注释,java,annotations,code-injection,Java,Annotations,Code Injection,我想要一个类PersonCollector通过具有注释PersonResolver的特定类注入字段PersonCollector检查带注释的类是否具有等于PersonCollector.personType字段的注释值。如果符合,逻辑将添加实现该注释的类,并将其分配给PersonCollector.personByType字段 我这里的问题是,我有一个接口Person和两个实现类CoolPerson和UncoolPerson,它们都用@PersonResolver注释和一个值进行注释,该值用枚举

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

我这里的问题是,我有一个接口Person和两个实现类CoolPersonUncoolPerson,它们都用@PersonResolver注释和一个值进行注释,该值用枚举PersonType指定它们的类型

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

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

以下是我想要实现的伪代码:

@PersonResolver

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonResolver {
  PersonType value();
}
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
    }
  }
  // ...
}
两种实现方式

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

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonResolver {
  PersonType value();
}
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
    }
  }
  // ...
}

您可以使用这样的库,它将扫描类路径以查找用
PersonResolver
注释的类型。例如,下面的代码将返回一组
java.lang.Class
注释为
@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());
Reflections=newreflections((“com.myproject”);
设置