gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:38:53 24 4
gpt4 key购买 nike

我想要一个类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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com