xetra11
xetra11

Reputation: 8837

How to get the annotations of an interfaces implementation class

I want a class PersonCollector to inject a field by specific classes which have the annotation PersonResolver. PersonCollector checks if the annotated class has a annotation value which equals the PersonCollector.personType field. If it complies, the logic will add the class which implements owns this annotation and assigns it to the PersonCollector.personByType field.

My problem here is, that I have an Interface Person and two implementing classes CoolPerson & UncoolPerson both annotated with the @PersonResolver annotation and a value which specifies their type with the Enum PersonType.

The only way to look for ALL implementations which hold the specific interface is to call on Person i.e. Person.class.getAnnotations(). This unfortunately only yields the annotations which are declared on the Person interface.

That is not what I actually want. I would love a list of all implementations of Person who own the Annotation - not Person itself.

Here is the pseudo/scratch code for what I want to achieve:

@PersonResolver

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

Both implementations

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

Upvotes: 1

Views: 4076

Answers (1)

ck1
ck1

Reputation: 5443

You can use a library such as Reflections that will scan the classpath for types annotated with PersonResolver. For example, the following code will return a set of java.lang.Classes annotated with @PersonResolver, and whose value() attribute equals 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());

Upvotes: 1

Related Questions