获取自定义注释的目标元素类型

时间:2019-10-03 21:02:10

标签: java java-annotations

我有一个自定义注释:

@Target({ElementType.METHOD}) // NOTE: ElementType is METHOD
public @interface MyAnnotation {
}

我有一个采用通用有界类型的通用类:

class MyWork<T extends Annotation> {
    T theAnnotation;

    public ElementType checkAnnotationElementType() {
        // how to get the target elementType of theAnnoation?
    }

}

我要实现的是获取T theAnnotation的目标元素类型。例如,我要实现的最终结果是:

 MyWork<MyAnnotation> foo = new MyWork();
 ElementType type = foo.checkAnnotationElementType(); // returns ElementType.METHOD

如何从通用类型变量theAnnotation中获取元素类型?

1 个答案:

答案 0 :(得分:1)

您可以执行类似的操作。从注释中获取注释。请注意,注释可以具有多个目标类型。

注意-您必须以某种方式实例化字段-构造函数似乎是一种好方法,可以忽略泛型。

ElementType[] target = new MyWork<>(MyAnnotation.class).checkAnnotationElementType();
class MyWork<T extends Annotation> {

    private final Class<T> annotationClass;

    public MyWork(Class<T> annotationClass) {
        this.annotationClass = annotationClass;
    }

    public ElementType[] checkAnnotationElementType() {
        return annotationClass.getAnnotation(Target.class).value();
    }
}
相关问题