注解

注解

自定义注解

格式

​ public @interface 注解名{

​ //注解属性

​ }

  • 注解的属性必须要有(),例如String value();
  • 注解使用的时候属性必须赋值,除非由默认值

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V4x18D18-1600749369022)(C:\Users\shiwenjing\AppData\Roaming\Typora\typora-user-images\image-20200922121503036.png
)]

  • 注解的特殊属性:value

    value属性如果只有一个value的情况下,value可以省略不写

    如果由多个属性,且多个属性没有默认值,value不能省略

元注解

元注解是用来注解自定义注解的

  • @Target 声明自定义注解可以使用的位置

    可使用的值在

    public enum ElementType {
        /** Class, interface (including annotation type), or enum declaration */
        TYPE,
    
        /** Field declaration (includes enum constants) */
        FIELD,
    
        /** Method declaration */
        METHOD,
    
        /** Formal parameter declaration */
        PARAMETER,
    
        /** Constructor declaration */
        CONSTRUCTOR,
    
        /** Local variable declaration */
        LOCAL_VARIABLE,
    
        /** Annotation type declaration */
        ANNOTATION_TYPE,
    
        /** Package declaration */
        PACKAGE,
    
        /**
         * Type parameter declaration
         *
         * @since 1.8
         */
        TYPE_PARAMETER,
    
        /**
         * Use of a type
         *
         * @since 1.8
         */
        TYPE_USE
    }
    
  • @Retention 用来标注注解的生命周期

    public enum RetentionPolicy {
        /**
         * Annotations are to be discarded by the compiler.
         */
        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.
         */
        CLASS,
    
        /**
         * Annotations are to be recorded in the class file by the compiler and
         * retained by the VM at run time, so they may be read reflectively.
         *
         * @see java.lang.reflect.AnnotatedElement
         */
        RUNTIME
    }
    

注解的解析

与注解相关的接口

  1. Annotation 注解类型,该类是所有注解的父类

  2. AnnotatedElement:该接口定义了与注解解析相关的接口

    所有的类成分Class,Method,Filed,Constructor都实现了该接口

    他们拥有的解析注解的能力:

    • Annotation[] getDeclaredAnnotation();

    • T getDeclaredAnnotation(Class annotationClass)
      有的解析注解的能力:

    • Annotation[] getDeclaredAnnotation();

    • T getDeclaredAnnotation(Class annotationClass)

    • boolean isAnnotationPresent(Class annotationClass)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值