代码之家  ›  专栏  ›  技术社区  ›  Tim B

看不到继承的批注

  •  0
  • Tim B  · 技术社区  · 7 年前

    我有课

    @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 没有。

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

    春天 ApplicationContext::getBeansWithAnnotation 在结果中返回这些bean Map 因此,这似乎在对注释进行某种深度解析。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Thomas    7 年前

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

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

    JavaDoc 在…上 java.lang.annotation.Inherited :

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

    了解 Class.getAnnotation() 你最终会遇到 private AnnotationData createAnnotationData(int classRedefinedCount) 它将迭代超类注释,并且仅在以下情况下添加注释 AnnotationType.getInstance(annotationClass).isInherited() 返回true。