java注解@Interface与Annotation

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
    String value() default "";
}

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
   String value() default "";
}

我有一个对象被@Configuration注解,那我怎么知道它还是被Component注解的?
@Interface 和接口Annotation是什么关系?
有一个注解了@Configuration的对象, obj.getClass().getAnnotation(Configuration.class).getClass()==Configu‌​ration.class 结果是false, obj.getClass().getAnnotation(Configuration.class) instanceof Configuration为true, obj.getClass().getAnnotation(Configuration.class) instanceof Component为false

阅读 6.6k
3 个回答
  1. Annotation 也可以获取自身的注解。

  2. @interface 是声明注解的关键字(与class/interface一样)

  3. obj.getClass().getAnnotation(Configuration.class).getClass() == Configu‌​ration.class 引用不同结果为false是正常情况。可以使用这种判断obj.getClass().getAnnotation(Configuration.class).getClass().getName().equals(Configu‌​ration.class.getName())

  4. @Component只是@Configuration 的注解声明,并不表示@Configuration就是@Component类型

另外上面这种用法叫Meta-Annotations在 spring-4.1.x 之后的的版本都支持这个功能,可以自定义Annotation,声明Meta-Annotations即可拥有相对的功能。
beans-meta-annotations
Spring Annotation Programming Model

@ContextConfiguration
public @interface MyTestConfig {

    @AliasFor(annotation = ContextConfiguration.class, attribute = "value")
    String[] xmlFiles();

    // ...
}

注:Meta-Annotations并不是Annotation的原生功能,只是在spring中实现了这种机制。如果单纯的使用原生的Annotation则需要自己解析Meta-Annotations实现相应的功能才行。

  1. 我有一个对象被@Configuration注解,那我怎么知道它还是被Component注解的?

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component  //<-这不是明摆着吗
    public @interface Configuration {
       String value() default "";
    }
  2. @Interface 和接口Annotation是什么关系?

    • 没听懂

  3. 讲道理getAnnotation(xx)以后直接去判断应该就可以了吧

  1. 楼上已经说过了,就不赘述了。
  2. 在 Annotation 的注释中第一句话就是: The common interface extended by all annotation types.

    即所有的注解类本质上都是继承了 `Annotation` 的接口。
  3. xx.getAnnotation(AnnotationClass) 这种做法取出来的不是注释类实例,而是一个 Proxy 实例,所以它的class != AnnotationClass
    @Component注解只是声明了 @Configuration 这个注解本身,并不意味着后者继承了前者,所以结合2,只有 class instanceof Annotation -> true

关于这点我的文章里有讲,只是第一次写文章,还在审核 :P

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题