【问题标题】:get target element type of custom annotation获取自定义注解的目标元素类型
【发布时间】:2019-10-03 21:02:10
【问题描述】:

我有一个自定义注释:

@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 中获取元素类型?

【问题讨论】:

    标签: java java-annotations


    【解决方案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();
        }
    }
    

    【讨论】:

    • 谢谢!我们可以从ElementType 得到ElementKind 的值吗?
    • @Leem.fin 考虑到它们的枚举名称不同,我想您需要自己进行映射。
    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多