java注解@Interface与Annotation
大家讲道理
大家讲道理 2017-04-18 10:16:47
[Java讨论组]
@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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
巴扎黑
  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)以后直接去判断应该就可以了吧

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号