【问题标题】:Not seeing inherited annotations看不到继承的注释
【发布时间】:2018-01-19 12:20:04
【问题描述】:

我有课

@ReadOnlyViewable(category = "Cache", description = "View the contents of a cache")
public class ReflectingCacheJmx<K, V> extends CacheJmx<K, V> {

我在上面添加了注释

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ReadOnlyViewable {
  String description();

  String category();
}

然后我有一个子类:

public class ObservableReflectingCacheJmx<K, V> extends ReflectingCacheJmx<K, V> {

还有一个子类:

public class CounterpartyCacheJmx extends ObservableReflectingCacheJmx<CounterpartyKey, Counterparty> {

当我获取CounterpartyCacheJmx 的实例并调用getClass().getAnnotation(ReadOnlyViewable.class) 时,我得到null 的结果。

另一方面,如果我调用 getClass().getSuperclass().getSuperclass().getAnnotation(ReadOnlyViewable.class),我会返回注释。

我认为getAnnotation 应该也返回超类的注释,而getDeclaredAnnotation 没有。

我的理解错了吗?我是否需要自己手动运行超类链(或使用第 3 方库来这样做)才能找到此注释?

Spring ApplicationContext::getBeansWithAnnotation 在生成的 Map 中返回这些 bean,因此似乎对注释进行了某种深度解析。

【问题讨论】:

    标签: java annotations


    【解决方案1】:

    您的注释缺少@Inherited 元注释:

    @Inherited
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface ReadOnlyViewable {
      String description();
    
      String category();
    }
    

    来自JavaDocjava.lang.annotation.Inherited

    表示一个注解类型是自动继承的。如果注解类型声明中存在 Inherited 元注解,并且用户在类声明上查询注解类型,并且类声明没有该类型的注解,则将自动查询该类的超类的注解类型。将重复此过程,直到找到此类型的注释,或到达类层次结构(对象)的顶部。

    查看Class.getAnnotation() 的实现,您最终会遇到private AnnotationData createAnnotationData(int classRedefinedCount),它将遍历超类注解,并且仅在AnnotationType.getInstance(annotationClass).isInherited() 返回true 时添加注解。

    【讨论】:

    • 完美,就是这样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2013-08-31
    • 2014-02-19
    相关资源
    最近更新 更多