欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Annotation 最终奥义,元注解

发布时间:2025/3/15 编程问答 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Annotation 最终奥义,元注解 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘Python工程师标准>>>

当你自定义出一个注解的时候,这个注解其实是没法使用的,因为你没有为注解指定的生存范围,生存的目标.。因此为了限定自定义注解,就出现了元注解这一个概念.

服务于注解的注解就是元注解。

其中元注解有一下的几个常见的注解:


    ***@Retention:注解的保留范围

     /**
     * Annotations are to be discarded by the compiler.
     */
        RetentionPolicy.SOURCE:注解存在于源文件中,在文件编译的时候,会被验证。 如果验证不通过 则报错的。  运行的时候是获取不到注解的。

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */

        RetentionPolicy.CLASS:注解存在于源字节码文件中,仅仅存在class的字节码文件中

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */

     RetentionPolicy.RUNTIME:注解存在于运行时, 在运行的时候,才能获取到的注解,这也是注解取代xml文件的重要核心。
    ***@Target:注解出现的位置
    @Documented: 用于指定被该元 Annotation 修饰的 Annotation 类将被 javadoc 工具提取成文档.
    @Inherited: 被它修饰的 Annotation 将具有继承性.如果某个类使用了被 @Inherited 修饰的 Annotation, 则其子类将自动具有该注解


例子:

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME ) public @interface Person {String  name() default "";int age();boolean married() default false;String []childrenName() default ""; }

最后一点,记着,注解是可以嵌套的!!!     一个注解里面可能还有其他注解作为成员变量,在这就不举例了

转载于:https://my.oschina.net/anyyang/blog/374192

总结

以上是生活随笔为你收集整理的Annotation 最终奥义,元注解的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。